Courses

Design Patterns in Laravel 11

Singleton: in Auth, Mail, Cache

Summary of this lesson:
- Authentication implementation using Singleton
- Mail system's use of Singleton pattern
- Cache system Singleton implementation
- Methods to retrieve Singleton instances in Laravel

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 17 lessons of this course? (72 min read)

You also get:

  • 69 courses (majority in latest Laravel 11)
  • Premium tutorials
  • Access to repositories
  • Private Discord