Laravel 5: Accessing the Authentication Manager With auth

April 14, 2018 —John Koster

The auth helper function is a convenience function to quickly access the Laravel authentication features; used without supplying any arguments for $guard, the auth helper function is an alternative to using the Auth facade. With no arguments, the auth function returns an instance of "Illuminate\Contracts\Auth\Factory" (which by default is an instance of "Illuminate\Auth\AuthManager").

#Signature

The signature of the auth function is:

1function auth(
2 $guard = null
3);

#Example Use

The following example shows to equivalent ways of retrieving the currently logged in user:

1use Illuminate\Support\Facades\Auth;
2 
3// Get the current user using the `Auth` facade.
4$currentUser = Auth::user();
5 
6// Get the current user using the `auth` helper.
7$currentUser = auth()->user();

You can quickly access any custom authentication guards by supplying an argument for the $guard parameter. For example if a custom guard was added with the name customGuard:

1 
2if (auth('customGuard')->attempt([
3 'email' => $email,
4 'password' => $password
5 ])) {
6 // Authentication passed.
7}

When $guard is set to null, the AuthManager instance will internally set $guard equal to the value of the auth.defaults.guard configuration key (by default this is set to web). The following code samples would produce the same results:

1 
2// Not passing anything for `$guard`.
3if (auth()->attempt([
4 'email' => $email,
5 'password' => $password
6 ])) {
7 
8}
9 
10// Passing the default configuration value for `$guard`.
11if (auth('web')->attempt([
12 'email' => $email,
13 'password' => $password
14 ])) {
15 
16}

Some absolutely amazing
people

The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.