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.phppublic function roles(){ return $this->belongsToMany(Role::class) ->using(RoleUser::class) ->withPivot(['team_id']);} // app/Models/RoleUser.php: notice extends Pivot, not Modeluse 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;