Back

Auth user in global scope


Hello. How can I access the current logged in user with auth()->user() in global scope defined in User model itself? When trying to do so, the application returns error 500 regarding maximum nesting level. I understand why this might be a problem, but is there a way to overcome this?

// User.php
protected static function boot() {
   parent::boot();
   static::addGlobalScope('test', function(Builder $builder) {
      $builder->where('id', auth()->id());
   });
}
TorchSK replied 2 months ago

Why are you using auth()? If you use Auth::user()->id , does it work?

BrakaTakl replied 2 months ago

TorchSK said:

Why are you using auth()? If you use Auth::user()->id , does it work?

It doesn't work with Auth::user() also (same error). What's wrong with auth()? I thought it was helper class.

BrakaTakl replied 2 months ago

In case someone stumbles upon this thread. I managed to cheat a bit. What I did is saved authenticated user id in session in LoginListener handle method:

// LoginListener.php
public function handle(Login $event) {
    session(['auth_user_id' => $event->user->id]);
}

And then in User model global scope used this value.

// User.php
protected static function boot() {
   parent::boot();
   if (session('auth_user_id')) {
      static::addGlobalScope('test', function(Builder $builder) {
         $builder->where('id', session('auth_user_id'));
      });
   }
}

Sign in to participate in this thread!



We'd like to thank these amazing companies for supporting us