Pivot Table with Extra Relations

In many-to-many relationship, your pivot table may contain extra fields, and even extra relationships to other Model.

Then generate a separate Pivot Model:

1php artisan make:model RoleUser --pivot

Next, specify it in belongsToMany() with ->using() method. Then you could do magic, like in the example.

1// in app/Models/User.php
2public function roles()
3{
4 return $this->belongsToMany(Role::class)
5 ->using(RoleUser::class)
6 ->withPivot(['team_id']);
7}
8 
9// app/Models/RoleUser.php: notice extends Pivot, not Model
10use Illuminate\Database\Eloquent\Relations\Pivot;
11 
12class RoleUser extends Pivot
13{
14 public function team()
15 {
16 return $this->belongsTo(Team::class);
17 }
18}
19 
20// Then, in Controller, you can do:
21$firstTeam = auth()->user()->roles()->first()->pivot->team->name;

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 22 courses (477 lessons, total 38 h 20 min)
  • 2 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord