Skip to main content

Black Friday 2025! Only until December 1st: coupon FRIDAY25 for 40% off Yearly/Lifetime membership!

Read more here

Singleton: in Auth, Mail, Cache

Premium
4 min read

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.


Authentication

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...

The Full Lesson is Only for Premium Members

Want to access all of our courses? (29 h 14 min)

You also get:

54 courses
Premium tutorials
Access to repositories
Private Discord
Get Premium for $129/year or $29/month

Already a member? Login here

Comments & Discussion

No comments yet…

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.