Many-to-many relationship in Laravel


I have this structure


I have the entity User, roles.The entity role_user NO, because it is not "necessary" When you create the migration for the role_user table, add some additional fields to it, for example, startdateRol dateFinRol. Now, when I get the user and their roles


This brings me a collection of roles, but I can not access the fields I mentioned before the role_user table, is that understood?

asked by Lucho 23.03.2018 в 20:18

4 answers


If you define additional fields in the intermediate table and wish to obtain them, you must define them in relation to the withPivot method:

return $this->belongsToMany('App\Role')->withPivot('column1', 'column2');

To access them, you do it by means of the pivot object:

echo $role->pivot->column1;

In the documentation you can find everything: link

answered by 23.03.2018 в 20:27

I pass the code of a relationship that I want to do, which would be the same as that of the users. A grandparent can have several applications and an application can belong to several grandparents: The grandfather class would be

 class Abuelo extends Model {

     public function aplicaciones(){
         return $this->belongsToMany(Aplicacion::class,'abuelos_aplicaciones','idAbuelo','idAplicacion')->withPivot('idAbuelo','idAplicacion');        

The Application class is

    protected $table='aplicaciones';

    protected $primaryKey='idAplicacion';         
     public function abuelos(){
         return $this->belongsToMany(Abuelo::class,'abuelos_aplicaciones','idAbuelo', 'idAplicacion')->withPivot('idAbuelo', 'idAplicacion');        

The migration of the tabpla pivot is

 public function up()
     Schema::create('abuelos_aplicaciones', function (Blueprint $table) {




and I'm trying to recover for example the dose field of the pivot table so


$ grandparents = Grandparent :: with ('Room') - > with ('Mutual') -> find ($ id);   dd ($ grandparents);

That brings me a grandfather

but nowhere is there anything that says pivot


Grandpa {# 285 ▼ #table: "grandparents" #primaryKey: "grandpa"


fillable: array: 3 [▶] #guarded: [] #connection: "mysql" #keyType: "int" + incrementing: true #with: [] #withCount: [] #perPage: 15 + exists: true + wasRecentlyCreated: false #attributes: array: 18 [▶] #original: array: 18 [▶] #casts: [] #dates: [] #dateFormat: null #appends: [] #events: [] #observables: [ ] #relations: array: 2 [▼

"Habitacion" => Habitacion {#290 ▶}
"Mutual" => Mutual {#289 ▶}   ]   #touches: []   +timestamps: true   #hidden: []   #visible: [] }

I hope you understand the code, but that's what happens, something is not working, I do not know what it is

answered by 26.03.2018 в 16:48

If, as you mentioned, you already have $usuarios=Usuario::where('idUsuario',"=",$id)->with('roles')->get(); running, then what you should do is: add withPivot() to your relationship function.

That is to say that within your model Usuario you must have a function called roles , then the code would be:

public function roles(){
    return $this->belongsToMany(Role::class,'role_user','user_id','role_id')->withPivot('fechaInicioRol ', 'fechaFinRol');

Then your query would be the same way:


And later you can use pivot to access the data.

For example in foreach

foreach($usuarios as $user){
    echo   $user->role->pivot->fechaInicioRol;

I hope I have helped you.

answered by 23.03.2018 в 22:50

I was able to solve it, I had a concept error, when the relation with the pivot table is created in the model, the foreign keys are not put, but the fields that are wanted to be taken from the pivot table - > withPivot ('startDay', 'rollDate'); That way it's fine, and then it recovers: $ user- > roles-> pivot- > start-dateRol; Thank you all for the help

answered by 27.03.2018 в 14:00