Laravel - Relationships - Attaching Detaching

Eloquent also provides methods to make working with many-to-many relationships more convenient. For example, let's imagine a user can have many roles and a role can have many users. You may use the attach method to attach a role to a user by inserting a record in the relationship's intermediate table:

    use App\Models\User;
    $user = User::find(1);

When attaching a relationship to a model, you may also pass an array of additional data to be inserted into the intermediate table:

    $user->roles()->attach($roleId, ['expires' => $expires]);

Sometimes it may be necessary to remove a role from a user. To remove a many-to-many relationship record, use the detach method. The detach method will delete the appropriate record out of the intermediate table; however, both models will remain in the database:

    // Detach a single role from the user...
    // Detach all roles from the user...

For convenience, attach and detach also accept arrays of IDs as input:

    $user = User::find(1);
    $user->roles()->detach([1, 2, 3]);
        1 => ['expires' => $expires],
        2 => ['expires' => $expires],