2
votes

I have three tables

  • users
  • groups
  • group_user (a pivot table which handles the membership of users in groups)

I am trying to delete the membership of a user from a group like this:

public function userDelete (Request $request, $userId)
{
    $gid = $request->group;
    $group = Group::find($gid);
    $user = User::find($userId);

    $user->groups->detach();

    // and the second method is :
    // foreach ($group->users as $user) {
    //     if ($user->pivot->user_id == $userId) {
    //         $user->detach($gid);
    //         
    //         break;
    //     }
    // }
}

I have tried it in may ways, but it always gives the error that the method detach() is not found:

BadMethodCallException in Macroable.php line 74: Method detach does not exist.

1
I seen the document is $user->roles()->detach($roleId); ,have you try $user->groups()->detach(); ?Hanson
could you post your user and group modelsjaysingkar

1 Answers

4
votes

When you do $user->groups->detach(), you call detach() on the resulting groups collection.

Instead, you should call the detach() method on the relation:

$user->groups()->detach();