title: Laravel Eloquent querying relationships
body: <p>I have created a messaging system for a project I am working on and appear to have hit a bit of a stumbling block.</p>
  
  <p>I have the following table structures (irrelevent columns omitted for clarity)</p>
  
  <pre><code>messages
  -------------------------
  from_id    to_id    spam
  
  users
  -------------------------
  id    group_id
  
  groups
  -------------------------
  id    access_level
  </code></pre>
  
  <p>the access level uses bitwise permissions </p>
  
  <pre><code>001 read
  010 write
  100 delete
  </code></pre>
  
  <p>so to read and write, the access level would be '3'</p>
  
  <p>users can have permissions revoked by site admin, so what I am trying to do is to select messages which have been sent to users where the sender still has write permissions.</p>
  
  <p>my models are set up as such (again only relevant parts shown)</p>
  
  <pre><code>class User extends Eloquent {
      public function group() {
          return $this-&gt;belongsTo('Group');
      }
  }
  
  class Message extends Eloquent {
      public function to() {
          return $this-&gt;belongsTo('User', 'to_id');
      }
      public function from() {
          return $this-&gt;belongsTo('User', 'from_id');
      }
  }
  </code></pre>
  
  <p>I have tried the following</p>
  
  <pre><code>Message::with(['from' =&gt; function($query)
  {
      $query-&gt;with(['group' =&gt; function($_query)
      {
          $_query-&gt;where('access_level', '&amp;', 2);
      }]);
  }])
  -&gt;where('to_id', Auth::user()-&gt;id)
  -&gt;get();
  </code></pre>
  
  <p>This gets the messages sent to the currently logged in user where the senders group's access level still enables the user to write messages (theoretically) however it is simply returning all the messages sent to the user.</p>
  
  <p>I have also tried specifically targeting the group (groups 6 and 7 are banned and unconfirmed accounts):</p>
  
  <pre><code>Message::with(['from' =&gt; function($query)
  {
      $query-&gt;whereNotIn('group_id', [6,7])
  }])
  -&gt;where('to_id', Auth::user()-&gt;id)
  -&gt;get();
  </code></pre>
  
  <p>which also returns all of the messages to the user.</p>
  
  <p><code>tl;dr</code></p>
  
  <p><strong>How, using Eloquent, would I select all messages sent to a user where the senders group has write permissions?</strong></p>
  
  <p><code>edit</code></p>
  
  <p>Of course, <code>::with</code> will not affect the messages which get pulled, as it only does lazy loading of joined tables.</p>