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:

php artisan make:model RoleUser --pivot

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

// in app/Models/User.php
public function roles()
{
return $this->belongsToMany(Role::class)
->using(RoleUser::class)
->withPivot(['team_id']);
}
 
// app/Models/RoleUser.php: notice extends Pivot, not Model
use Illuminate\Database\Eloquent\Relations\Pivot;
 
class RoleUser extends Pivot
{
public function team()
{
return $this->belongsTo(Team::class);
}
}
 
// Then, in Controller, you can do:
$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:
  • 68 courses (1183 lessons, total 43 h 18 min)
  • 90 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord

Recent New Courses