I have the following problem when trying to make an auto relationship with Laravel 5. I want to make a user registration, where users can have other users linked, creating an authoring N x N, user_user;
The user will have a status, and this status is another model.
class User extends Authenticatable{
protected $fillable = [
'name', 'email', 'password', 'status_id'
];
...
class Vinculo extends Model{
protected $fillable = [
'id', 'user_id', 'vinculo_id'
];
....
class StatusUser extends Model{
protected $fillable = [
'id', 'nome',
];
..
and in my UserController I query the user with status
public function show($id){
$result = $this->context->with('statususers')->find($id);
...
that returns json,
{
"id": 2,
"name": "aa",
"email": "[email protected]",
"statususers": {
"id": 2,
"nome": "Ativo"
}
}
..
Now my question is, how to consult all the users related to a specific user, and that in the linked users can also be displayed the status of each one,
Relationship in the User class
public function vinculos(){
return $this->belongsToMany('App\User', 'vinculos', 'user_id', 'vinculos_id');
}
...
I modify the show method, including the relationship bindings
public function show($id){
$result = $this->context->with('statususers')->with('vinculos')->find($id);
The relationship is ok, but it's not returning the statuses of the linked users, that's the problem.
{
"id": 2,
"name": "aa",
"email": "[email protected]",
"remember_token": "Y7cc9OHpKalEkKivihETU2LQeNftGWZ1hqVH0v2nM1z0DZ3dUe3emwsIDxec",
"statususers": {
"id": 2,
"nome": "Ativo"
},
"vinculos": [
{
"id": 3,
"name": "bb",
"email": "[email protected]",
"pivot": {
"user_id": 2,
"amigo_id": 3
}
}
{
"id": 4,
"name": "cc",
"email": "[email protected]",
"pivot": {
"user_id": 2,
"amigo_id": 3
}
}
]
}
This is the big question, if my related object is of the class User, because the other users do not also show their respective status objects, same as the parent record of the links? Seeing that all other attributes of the User class are displayed correctly, but the status object is missing.
Can anyone help me?