In some cases, Laravel needs to return the same object instance every time it is requested. For this, it uses the Singleton pattern in multiple places.
In the case of authentication, you want to avoid fetching the user from the database or any other source every time you need to access the authenticated user.
Instead, you create a Singleton instance and store the authenticated user in it:
Illuminate/Auth/AuthServiceProvider.php
protected function registerAuthenticator(){ $this->app->singleton('auth', fn ($app) => new AuthManager($app)); $this->app->singleton('auth.driver', fn ($app) => $app['auth']->guard());}
This registers the auth
(Auth Facade) and auth.driver
services as singletons. Inside, it creates new instances of AuthManager
and Guard
, respectively.
Inside the AuthManager
class, it will create a User resolver that will be used to resolve the authenticated user:
Illuminate/Auth/AuthManager.php
/** * Create a new Auth manager instance. * * @param \Illuminate\Contracts\Foundation\Application $app * @return void */public function __construct($app){ $this->app = $app; $this->userResolver = fn ($guard = null) => $this->guard($guard)->user();}
And this then allows us to retrieve the authenticated user from the auth
Singleton:
Auth::user()auth()->user()
Which will always return the same instance of the...