HomeLARAVELLaravel Guards: A Complete Guide

Laravel Guards: A Complete Guide

Laravel is a powerful PHP framework that simplifies web application development. One of its key features is a robust authentication system. At the core of this system lies the concept of guards. Understanding guards is crucial for building applications with multiple user roles or authentication mechanisms.


What are Laravel Guards?

In Laravel, a guard defines how users are authenticated for each request. It acts as a layer that determines how to check if a user is logged in and which user provider to use to retrieve user information.

Think of a guard as the authentication driver that manages user sessions or tokens.

Laravel comes with two main authentication drivers:

  1. Session Guard – Used for typical web applications where login status is maintained using sessions and cookies.
  2. Token Guard – Used for APIs where authentication is done using tokens, typically API Tokens or JWT.

How Guards Work in Laravel

Guards rely on user providers. The user provider defines how users are retrieved from storage, typically a database.

  • Guard → Handles authentication mechanism.
  • User Provider → Handles retrieving user data from the storage.

For example, in config/auth.php:

'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],

    'api' => [
        'driver' => 'token',
        'provider' => 'users',
        'hash' => false,
    ],
],

'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => App\Models\User::class,
    ],
],
  • web guard uses the session driver and retrieves users from the users provider.
  • api guard uses the token driver with the same user provider.

Default Guard

The default guard is defined in config/auth.php:

'defaults' => [
    'guard' => 'web',
    'passwords' => 'users',
],

Laravel uses the web guard for web requests unless specified otherwise.


Why Guards Are Useful

  1. Multiple Authentication Systems: You can have different guards for users, admins, and API clients.
  2. Flexible Authentication: Choose between session-based, token-based, or custom authentication.
  3. Role-Based Access Control: Guards make it easier to restrict certain areas of your application to specific users.

Creating Custom Guards

Sometimes, the default guards are not enough. You can create custom guards.

Example: A custom guard for admin users:

  1. Define a new guard in config/auth.php:
'guards' => [
    'admin' => [
        'driver' => 'session',
        'provider' => 'admins',
    ],
],
'providers' => [
    'admins' => [
        'driver' => 'eloquent',
        'model' => App\Models\Admin::class,
    ],
],
  1. Create Admin model:
php artisan make:model Admin -m
  1. Protect routes using middleware:
Route::middleware('auth:admin')->group(function () {
    Route::get('/admin/dashboard', [AdminController::class, 'index']);
});

Now only authenticated admins can access the /admin/dashboard route.


Using Guards in Code

You can explicitly use a guard in your controllers or middleware:

// Check if a user is logged in using the 'web' guard
if (Auth::guard('web')->check()) {
    $user = Auth::guard('web')->user();
}

// Authenticate using the 'admin' guard
if (Auth::guard('admin')->attempt(['email' => $email, 'password' => $password])) {
    return redirect()->intended('/admin/dashboard');
}

Common Use Cases of Guards

  1. Multiple User Roles
    • Users, Admins, Managers, etc. Each with separate authentication.
  2. API Authentication
    • API tokens or JWT for stateless authentication.
  3. Third-Party Authentication
    • Social login or external authentication systems.

Tips for Working with Guards

  • Always specify the guard in routes if you have multiple guards.
  • Don’t mix session guards and token guards unless necessary.
  • Use middleware auth:guard_name to protect routes.
  • Test each guard independently to ensure correct authentication behavior.

Conclusion

Laravel guards are a powerful tool for managing authentication in complex applications. They allow you to:

  • Define multiple ways to authenticate users.
  • Protect different types of users and routes.
  • Easily extend authentication with custom guards.

By understanding guards and providers, you can implement secure, flexible, and maintainable authentication systems in your Laravel applications.

What is a Guard in Laravel?

A Guard defines how users are authenticated for each request.
It specifies the logic of authentication (e.g., using sessions, tokens, etc.).

Difference between Guards and Providers in Laravel?

Guards → Define how users are authenticated (e.g., session, token).
Providers → Define how users are retrieved from the database.

‘guards’ => [
‘web’ => [
‘driver’ => ‘session’,
‘provider’ => ‘users’,
],
‘admin’ => [
‘driver’ => ‘session’,
‘provider’ => ‘admins’,
],
],

Where are Guards defined in Laravel?

In the config/auth.php file under the guards array.

What are the default Guards in Laravel?

web → Uses sessions and cookies (for browser authentication).
api → Uses tokens (like Passport, Sanctum, JWT).

Can you create a custom Guard in Laravel?

Yes.
Steps:
Define guard in config/auth.php.
Create custom authentication logic (via provider or custom class).
Register the guard in AuthServiceProvider.

How do you switch between multiple Guards?

Use the Auth::guard('guard_name') method.
Example:

Auth::guard('admin')->attempt($credentials);

How to get currently logged-in user from a specific guard?

$user = Auth::guard(‘admin’)->user();

Difference between Auth::check() and Auth::guard()->check()?

Auth::check() → Uses default guard (web).
Auth::guard('api')->check() → Uses the specified guard.

How to protect routes with different Guards?

In routes/web.php or routes/api.php:

Route::middleware('auth:admin')->group(function () { // Only admin users can access });

When should you use multiple Guards?

When you have different types of users with separate login systems.
Example: admin, customer, vendor.

How is Laravel Guard related to Middleware?

Middleware checks authentication status using Guards.
Example: auth:admin middleware checks login with admin guard.

What is the default Guard in Laravel and how to change it?

Default → web.
To change: update defaults.guard in config/auth.php.

How to log out a user from a specific Guard?

Auth::guard(‘admin’)->logout();

How to authenticate users without using Guard directly?

You can use attempt(), login(), or once() methods:

Auth::attempt(['email' => $email, 'password' => $password]);

Example use case: Guards with Admin and User logins

Admin guard → Handles admin login separately.
Web guard → Handles normal user login.
This prevents conflicts when both roles exist in the system.

Share: 

No comments yet! You be the first to comment.

Leave a Reply

Your email address will not be published. Required fields are marked *