In Laravel, you can detach related records using Eloquent relationships by following these steps:
Define the relationship in your Eloquent model:
class User extends Model
{
public function roles()
{
return $this->belongsToMany(Role::class);
}
}
Retrieve the user record along with its related records:
find
, findOrFail
, or any other filtering methods.$user = User::findOrFail($userId);
Detach the related records:
detach
method on the relationship to detach the related records.$user->roles()->detach();
detach
method to detach only specific related records:$user->roles()->detach([1, 2, 3]);
$user->roles()->detach([1, 2, 3], ['verified' => false]);
Save the changes:
$user->save();
By following these steps, you can detach related records using Eloquent relationships in Laravel.