PHP
Manage Many-to-Many Relationships with Eloquent Attach and Detach
Learn to easily add or remove related models in a many-to-many relationship using Eloquent's `attach`, `detach`, and `sync` methods for pivot tables.
// Assuming a User model with a 'roles' many-to-many relationship
use App\Models\User;
use App\Models\Role;
$user = User::find(1);
$adminRole = Role::where('name', 'admin')->first();
$editorRole = Role::where('name', 'editor')->first();
// Attach a role (add to pivot table)
$user->roles()->attach($adminRole->id);
// Attach with pivot table attributes
$user->roles()->attach($editorRole->id, ['assigned_at' => now()]);
// Detach a role (remove from pivot table)
$user->roles()->detach($adminRole->id);
// Sync roles (attaches new ones, detaches missing ones, updates existing)
// $user->roles()->sync([1, 2, 3]); // Replaces all current roles with IDs 1, 2, 3
// Sync with pivot data for existing relationships
// $user->roles()->sync([
// 1 => ['expires_at' => now()->addYear()],
// 2,
// ]);
// Toggle a relationship (attaches if not attached, detaches if attached)
// $user->roles()->toggle($adminRole->id);
How it works: For many-to-many relationships, Eloquent provides `attach`, `detach`, `sync`, and `toggle` methods to manage records in the intermediate pivot table. `attach` adds a record, `detach` removes it. `sync` efficiently synchronizes the relationship by attaching new IDs, detaching missing ones, and keeping existing ones, optionally updating pivot data. `toggle` conveniently switches the state of a single relationship.