Reputation: 377
How can I query in my pivot table if the user already exist in the group ?
I have USERS table, GROUPS table, and GROUP_USER table. In the group user table wherein the id's of the two tables stored so I want to check in my condition if he/she already existed there will be a message.
Here is the code of my current query statement to check if it is existed:
Group::where('user_id', '=', $user)
->where('group', '=', $group->user->id)
->first;
Answer:
if ($group) {
if ($group->users()->where('users.id', $user)->exists()) {
Session::flash('info', 'You\'re already part of the group', $group->group_name);
} else {
$group->users()->attach($user);
Session::flash('success', 'You are now part of the group' . ' ' . $group->group_name);
}
} elseif ($false) {
Session::flash('danger', 'Invalid group code');
}
return back();
Upvotes: 0
Views: 1422
Reputation: 13693
You can use whereHas()
method like this:
Group::whereHas('users', function($q) use($user) {
$q->where('id', $user->id); // check for single user id
$q->whereIn('id', $user_ids_arr); // or use whereIn & pass array of user ids
});
Or if you want a boolean
in return you can use exists()
method like this:
$group = Group::find($group_id);
$user_exists = $group->users()->where('id', $user_id)->exists();
// return 'true' if user exits else returns 'false'
UPDATE
If you want to associate users with a group you can use attach()
like this:
$group->users()->attach($user_id);
See more about Updating Many to Many Relationships
Updated Code - Comments
$user_arr = $group->users->pluck('id')->all(); // returns an array
$valid_user = in_array($user->id, $user_arr); // true / false
if ($group) {
if($valid_user) {
Session::flash('info', 'Already part of this group');
} else {
$group->users()->attach($user->id);
}
} else {
Session::flash('danger', 'Wrong Group Code!');
}
return redirect()->back();
Hope this helps!
Upvotes: 0
Reputation: 17658
You can try it as:
$group->users()->where('users.id', $user)->exists()
To insert in pivot table you can use attach
method as:
$group->users()->attach($user_id)
Update
From the comments, your code should be as:
if ($group) {
if($group->user()->where('users.id', $user)->exists()) {
Session::flash('info', 'Already part of this group');
} else {
$group->users()->attach($user);
Session::flash('success', 'You are now part of the group!');
}
} else {
Session::flash('danger', 'Wrong Group Code!');
}
return redirect()->back();
Upvotes: 1