Ijaz Khan
Ijaz Khan

Reputation: 75

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

I have three tables

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.

Upvotes: 2

Views: 5614

Answers (1)

jedrzej.kurylo
jedrzej.kurylo

Reputation: 40909

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();

Upvotes: 4

Related Questions