Support the ongoing development of Laravel.io →
Authentication Session

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());
   });
}
Last updated 2 years ago.
0

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

0

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.

0

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'));
      });
   }
}
Last updated 7 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

BrakaTakl brakatakl Joined 16 Jul 2016

Moderators

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

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.