How to detach related records using Eloquent relationships in Laravel?

In Laravel, you can detach related records using Eloquent relationships by following these steps:

  1. Define the relationship in your Eloquent model:

    • For example, if you have a User model that has many roles, you would define the relationship like this:
    class User extends Model { public function roles() { return $this->belongsToMany(Role::class); } }
  2. Retrieve the user record along with its related records:

    • To detach related records, you need to first retrieve the user model using Eloquent query methods like find, findOrFail, or any other filtering methods.
    $user = User::findOrFail($userId);
  3. Detach the related records:

    • Once you have retrieved the user model, you can use the detach method on the relationship to detach the related records.
    $user->roles()->detach();
    • You can also pass an array of role IDs to the detach method to detach only specific related records:
    $user->roles()->detach([1, 2, 3]);
    • If the relationship defines any additional columns on the intermediate table, you can supply the intermediate table columns when detaching records:
    $user->roles()->detach([1, 2, 3], ['verified' => false]);
  4. Save the changes:

    • Finally, save the changes to persist the detached relationship records.
    $user->save();

By following these steps, you can detach related records using Eloquent relationships in Laravel.