PHP

Manage Many-to-Many Relationships with Pivot Data in Eloquent

Learn to define and interact with many-to-many relationships in Laravel Eloquent, including how to attach, detach, sync, and access pivot table attributes.

// In App\Models\Role.php (e.g., User has many Roles, Role has many Users)
class Role extends Model
{
    public function users()
    {
        return $this->belongsToMany(User::class)->withTimestamps()->withPivot('status', 'notes');
    }
}

// In App\Models\User.php
class User extends Model
{
    public function roles()
    {
        return $this->belongsToMany(Role::class)->withTimestamps()->withPivot('status', 'notes');
    }
}

// Attaching a role to a user with pivot data
$user = App\Models\User::find(1);
$roleId = 2;
$user->roles()->attach($roleId, ['status' => 'active', 'notes' => 'Initial assignment']);

// Detaching a role
$user->roles()->detach($roleId);

// Syncing roles (adds/removes to match provided array)
$user->roles()->sync([1, 3 => ['status' => 'pending']]); // Role 3 gets specific pivot data

// Syncing without detaching others
$user->roles()->syncWithoutDetaching([4]);

// Accessing pivot data
foreach ($user->roles as $role) {
    echo $role->name . ' - Status: ' . $role->pivot->status . '
';
}

// Using a custom pivot model
// In App\Models\UserRole.php (pivot model)
class UserRole extends Pivot
{
    protected $table = 'role_user'; // If not convention-based
}

// In App\Models\User.php
public function roles()
{
    return $this->belongsToMany(Role::class)->using(UserRole::class)->withPivot('status', 'notes');
}
How it works: Many-to-many relationships in Eloquent are handled using a pivot table. The `belongsToMany` method defines this relationship. By adding `withPivot()` and `withTimestamps()`, you can interact with extra columns on the pivot table. Methods like `attach()`, `detach()`, and `sync()` manage the associations, while `syncWithoutDetaching()` allows adding new associations without removing existing ones. The `pivot` property on the related model allows accessing these intermediate table attributes directly. Custom pivot models offer even more control over pivot table data.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs