title: Laravel 5.8: How to resolve auth()->user() inside Global Scope's apply method?
body: <p>I need to apply specific global scope only if authenticated user's role is equal to something. So that user with certain role will only be able to execute queries on a given subset of records.</p>
  
  <p>I can easily deal with User model (of currently logged in user) but not inside scope's apply method.</p>
  
  <blockquote>
    <p><a href="https://github.com/laravel/framework/issues/22316#issuecomment-349548374" rel="noreferrer">https://github.com/laravel/framework/issues/22316#issuecomment-349548374</a></p>
    
    <p><strong>The scope constructor executes very early, before the auth middleware 
    has run</strong>. Resolve the user within the apply method, not in the constructor.</p>
  </blockquote>
  
  <p>OK, so I'm inside the <code>apply</code> method:</p>
  
  <pre><code>&lt;?php
  
  namespace App\Scopes;
  
  use Illuminate\Database\Eloquent\Scope;
  use Illuminate\Database\Eloquent\Model;
  use Illuminate\Database\Eloquent\Builder;
  
  class UserScopeForSalesContactAdmin implements Scope
  {
      /**
       * Apply the scope to a given Eloquent query builder.
       *
       * @param  \Illuminate\Database\Eloquent\Builder  $builder
       * @param  \Illuminate\Database\Eloquent\Model  $model
       * @return void
       */
      public function apply(Builder $builder, Model $model)
      {
          dd('within apply', auth()-&gt;user());
          dd(auth()-&gt;user()); // won't work
  
          $builder-&gt;where('foo', '=', 'something from currently logged in user');
      }
  }
  </code></pre>
  
  <p>Obviously second <code>dd</code> gives:</p>
  
  <blockquote>
    <p>Maximum function nesting level of '512' reached, aborting!</p>
  </blockquote>
  
  <p>How to resolve this? I imagine I should call IOC container via <code>app()-&gt;make()</code> but then?</p>
  
  <p>Thanks for any hints.</p>
  
  <p>edit: I think I see what's causing the infinite loop (<a href="https://github.com/laravel/framework/issues/26113" rel="noreferrer">https://github.com/laravel/framework/issues/26113</a>) but still I need to find a best way to obtain the User…</p>