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;
Enjoyed This Tip?
Get access to all premium tutorials, video and text courses, and exclusive Laravel resources. Join our community of 10,000+ developers.
Recent Courses
Laravel Modules and DDD
16 lessons
1 h 59 min
How to Build Laravel 12 API From Scratch
28 lessons
1 h 21 min
Filament 4 From Scratch
28 lessons
2 h 25 min