How to query in pivot table laravel
<p>How can I query in my pivot table if the user already exist in the group ?</p>

<p>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.</p>

<p>Here is the code of my current query statement to check if it is existed:</p>

<pre><code>Group::where('user_id', '=', $user)
     -&gt;where('group', '=', $group-&gt;user-&gt;id)
     -&gt;first;
</code></pre>

<p>Answer:</p>

<p><code>if ($group) {
            if ($group-&gt;users()-&gt;where('users.id', $user)-&gt;exists()) {
                Session::flash('info', 'You\'re already part of the group', $group-&gt;group_name);
            } else {
                $group-&gt;users()-&gt;attach($user);
                Session::flash('success', 'You are now part of the group' . ' ' . $group-&gt;group_name);
            }
        } elseif ($false) {
            Session::flash('danger', 'Invalid group code');
        }
        return back();</code></p>