Obtain data from a Pivot laravel table


I'm trying to get the data from my pivot table.

Right now the way I do it is like this

 $sala = Saluser::where('sala_id',$sala->id)->pluck('user_id');

$usuario = User::whereIn('id',$sala)->get();

The drawback is that I must make two inquiries, which in a relationship. one to many, simply applying the With me loads the related data. With eloquent.

but this time is from many to many


I have

|ID   |
|Name |
|etc  |

|Id      |
|user_id |
|sala_id |

|Salas |
|id    |
|etc   |

My relationships are in this way: from the user model

 public function Salas() {

return $this->belongsToMany(Sala::class,'salusers');

from the Sala model

public function Salas(){

return $this->belongsToMany(User::class,'salusers');

from the pivot.

public function User(){
return $this->belongstoMany(User::class,'user_id');

 public function Sala(){

return $this->belongstoMany(Sala::class,'sala_id');


- In summary

I am sending the room ID:

And I need to get

all the information in a room

with all the users that are registered to the.

asked by Alex Burke Cooper 14.11.2018 в 22:34

1 answer


Why do not you just use the relationship?


public function miFuncion(Request $request)
    // id de sala
    $id_sala = $request->get('id');
    // instancia sala
    $sala = Sala::with('users')->find($id_sala);

    return $sala;

With this you already have the users

echo $sala->users;

What I do not understand is your intermediate model, are you using a custom model for the Pivot? If so, make it extend the class Pivot instead of model and when you define the relationships in User and Sala define them as follows:


public function users()
    return $this->belongsToMany('App\User')

PS: In this intermediate model it is not necessary to define the relationships with the other models.

answered by 15.11.2018 в 15:53