Laravel Application Helper: auth

November 20, 2016 —John Koster

auth($guard = null)

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

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

1<?php
2 
3use Illuminate\Support\Facades\Auth;
4 
5// Get the current user using the `Auth` facade.
6$currentUser = Auth::user();
7 
8// Get the current user using the `auth` helper.
9$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<?php
2 
3if (auth('customGuard')->attempt([
4 'email' => $email,
5 'password' => $password
6 ])) {
7 // Authentication passed.
8}

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 web). The following code samples would produce the same results:

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

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.