← Back to all snippets
PHP

Managing Many-to-Many Relationships with Pivot Tables

Learn to define and interact with many-to-many relationships in Laravel Eloquent, including accessing and manipulating data on the pivot (intermediate) table with methods like `attach`, `detach`, and `sync`.

// In App\Models\Role.php
public function users()
{
    return $this->belongsToMany(App\Models\User::class)->withTimestamps();
}

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

// Attaching a role to a user
$user = App\Models\User::find(1);
$user->roles()->attach(2, ['status' => 'active', 'expires_at' => now()->addYear()]);

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

// Syncing roles (attaches, detaches, updates as needed)
$user->roles()->sync([1, 3 => ['status' => 'pending']]);

// Accessing pivot data
foreach ($user->roles as $role) {
    echo $role->pivot->status;
    echo $role->pivot->expires_at;
}
How it works: Many-to-many relationships are defined using `belongsToMany()` and typically involve a pivot table to store the association. The `withPivot()` method allows you to specify additional columns on the pivot table that you wish to access. Methods like `attach()`, `detach()`, and `sync()` provide convenient ways to manage these relationships, while the `pivot` property allows accessing the intermediate table's data directly from the related model.

Need help integrating this into your project?

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

Hire DigitalCodeLabs