TIP 23 / 36

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:

bash
php artisan make:model RoleUser --pivot

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

code
// 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);
    }
}

// In a controller, access the related records like this:
$firstTeam = auth()->user()->roles()->first()->pivot->team->name;