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 Model10use Illuminate\Database\Eloquent\Relations\Pivot;11 12class RoleUser extends Pivot13{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;