Laravel Eloquent - Attach vs Sync

Here's an example that demonstrates the difference between using attach() and sync() in Laravel Eloquent:

Let's say we have two models - User and Role. A user can have multiple roles, and a role can be assigned to multiple users. This is a many-to-many relationship, and we have a pivot table called role_user to manage the relationships.

// Attach a role to a user
$user = User::find(1);
$user->roles()->attach(2); // Attaches role with id 2 to user with id 1

// Now the user has role 2 in addition to any existing roles.

// Sync roles for a user
$user = User::find(1);
$user->roles()->sync([2, 3]); // Syncs roles 2 and 3 with user 1

// Now the user has only roles 2 and 3 and any other roles that the user had earlier are removed.

As you can see, attach() simply adds a new role to the user without affecting any existing roles, while sync() replaces the user's roles with the specified roles.

Watch a course Learn object oriented PHP

Another example could be in a blog website where a user can have multiple posts, and a post can be assigned to multiple users.

// Attach a post to a user
$user = User::find(1);
$user->posts()->attach(2); // Attaches post with id 2 to user with id 1

// Now the user has post 2 in addition to any existing posts.

// Sync posts for a user
$user = User::find(1);
$user->posts()->sync([2, 3]); // Syncs post 2 and 3 with user 1

// Now the user has only post 2 and 3 and any other posts that the user had earlier are removed.

In this example, attach() just adds the post with id 2 to the user's post collection, while sync() replaces the user's post collection with the specified posts.