Dorokhov.codes

12. Authentication

Laravel has new starter kits for React, Vue, and Livewire, including the option of using WorkOS AuthKit for user authentication. The WorkOS offers social authentication, passkeys, and SSO support.

Here are some examples of how you can implement authentication processes:

Case
Login and registration
Email verification

Basics

To fully understand how authentication works, it’s important to be familiar with concepts like cookies and sessions.

  • Cookies store data on the client-side (in the user’s browser). They are included with every HTTP request and are limited in size (~4KB). Cookies are useful for saving user preferences.
  • Sessions store data on the server-side. Only a session ID is stored in the user’s browser via a cookie. Sessions are more secure and can hold larger amounts of data. They are commonly used for user authentication and temporary data like shopping carts.

Session

A user will provide their username and password via a login form. If these credentials are correct, the application will store information about the authenticated user in the user’s session.

What Laravel stores in the session after login:

Session Key Description
_token CSRF token used to protect forms and requests
_previous The previous URL visited by the user (used for redirects)
_flash Temporary data meant for the next request only (e.g., success messages)
login_web_xxx (optional) Cache key to prevent multiple concurrent logins if LoginLimiter is used
errors Validation errors (often after a redirect)
url.intended The URL the user originally wanted to access (used to redirect back after login)
login_ + sha1(guard) The authenticated user ID (e.g., login_web => 1, where 1 is the user ID)

A cookie issued to the browser contains the session ID.

Facades

Laravel includes built-in authentication and session services which are typically accessed via the Auth and Session facades. They provide methods that allow you to verify a user’s credentials and authenticate the user. In addition, these services will automatically store the proper authentication data in the user’s session and issue the user’s session cookie.

Illuminate\Support\Facades\Auth

The attempt method accepts an array of key / value pairs as its first argument. The values in the array will be used to find the user in your database table.

if (Auth::attempt(['email' => 'andrew@dorokhov.dev', 'password' => 'query123'])) {
    // The attempt method will return true if authentication was successful.
}

If the credentials are valid, Laravel stores the user’s ID in the session, typically like:

$_SESSION['_login_user_id'] = 123; // conceptually

If you use:

Auth::attempt($credentials, true);

Laravel will write a remember_token to the database (typically in the users table) and set a remember_web_xxx cookie.

UPDATE users SET remember_token = '...' WHERE id = 123

When Laravel detects the remember_web_xxx cookie, it automatically logs the user in, creates a new session, and regenerates the session ID. After this, Laravel no longer needs the remember_me cookie during the lifetime of that session, because the user is now authenticated via the standard session mechanism ($_SESSION).

Getting the user data:

use Illuminate\Support\Facades\Auth;

// Retrieve the currently authenticated user...
$user = Auth::user();

// Retrieve the currently authenticated user's ID...
$id = Auth::id();

To determine if the user making the incoming HTTP request is authenticated:

use Illuminate\Support\Facades\Auth;

if (Auth::check()) {
    // The user is logged in...
}

Logging in using the user object:

Auth::login($user);

Logging out:

Auth::logout();

Other

The Request class also has a method to get the authenticated user:

public function view(Request $request): RedirectResponse
{
    $user = $request->user();
    // ...
}

Providers

In Laravel, providers are important components of the authentication system that define from where user information is loaded.

Each provider is identified by a name (like admins or clients) — this is just a logical group name.

'providers' => [
    'admins' => [
        'driver' => 'eloquent',
        'model' => App\Models\Admin::class,
    ],
    'clients' => [
        'driver' => 'eloquent',
        'model' => App\Models\Client::class,
    ],
],

The driver option defines how users are fetched:

  • eloquent (default) — uses a Laravel Eloquent model.
  • database — uses raw database queries (no model).

When using eloquent, you must specify the model class that represents the users in this group (e.g., Admin, Client). Laravel will use this model to retrieve users from the database.

Guards

In Laravel, a guard defines how users are authenticated for each request. A guard consists of two main parts:

  1. Driver – defines how authentication is done:
    • session – standard session-based login (used in web apps)
    • token – simple token-based authentication (for APIs)
    • sanctum, passport, or custom drivers – for advanced API auth
  2. Provider – tells Laravel where to get user info (e.g., from users or admins provider)

How it works

'guards' => [
    'admin' => [
        'driver' => 'session',
        'provider' => 'admins',
    ],
],

When you use something like:

Auth::guard('admin')->check();

Laravel:

  1. Uses the admin guard.
  2. Checks the session to see if the user is authenticated.
  3. Uses the admins provider to load the user data.

Blade

In your Blade templates you can use the @auth and @guest directives.

@auth
    // The user is authenticated...
@endauth

@guest
    // The user is not authenticated...
@endguest

If needed, you may specify the authentication guard that should be checked when using the @auth and @guest directives:

@auth('admin')
    // The user is authenticated...
@endauth

@guest('admin')
    // The user is not authenticated...
@endguest