Reputation: 75
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.
Upvotes: 2
Views: 5614
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