title: Grab variable outside from within closure
body: <p>Considering this closure:</p>
  
  <pre><code>$users = User::with(array('posts' =&gt; function($query) {
      $query-&gt;orderBy('created_at', 'desc');
  }))-&gt;get();
  </code></pre>
  
  <p>How do I pass <code>$query</code> to <code>get()</code> such as <code>-&gt;get('query')</code>?</p>
  
  <p>If this is even possible.</p>
  
  <p><strong>Update</strong>:</p>
  
  <p>This is a follow up to the accepted answer.</p>
  
  <p>Below is the resulting code, for a similar situation, based in <code>$query-&gt;getRelation()</code> tip.</p>
  
  <pre><code>$query = Ticket::with(array('user' =&gt; function($q) use ($search) {
      $q-&gt;where('name', 'LIKE', '%'. $search .'%')-&gt;orWhere('username', 'LIKE', '%'. $search .'%');
  }));
  
  return $query-&gt;whereIn('user_id', $query-&gt;getRelation('user')-&gt;lists('id'))-&gt;paginate(10);
  </code></pre>
  
  <p>Another one of the many ways to achieve it in Eloquent.</p>