0

I have a Laravel application where I want to get Auth::user in my model. However, when I do Auth::check() in the model, it returns false whereas in the controller it returns true.

protected static function boot()
{
    parent::boot();

    if (Auth::check()){ //returns false
        // do my stuff
    }
}
Karl Hill
  • 12,937
  • 5
  • 58
  • 95
tayyab_fareed
  • 559
  • 9
  • 15

1 Answers1

4

I'm pretty sure the boot function on models is executed before the AuthProvider is loaded. Otherwise the default auth provider couldn't be able to use the User model.

Because of this, you do not have access to the user details in the boot function.

Jerodev
  • 32,252
  • 11
  • 87
  • 108
  • You answer seems legit but https://stackoverflow.com/questions/50564362/laravel-5-want-to-access-auth-user-id-in-model here they are doing something similar – tayyab_fareed Dec 04 '18 at 14:52
  • Yes, the function would work fine if you use it in code that you call manually when Laravel has been loaded. It just won't work in the boot function. – Jerodev Dec 04 '18 at 14:58
  • It also sounds like a code smell to use `Auth::check()` in a model function, to be honest. It may even prevent you from using certain functionality within console commands, for example. – Namoshek Dec 04 '18 at 15:57