0
0
Laravelframework~5 mins

Authentication guards in Laravel

Choose your learning style9 modes available
Introduction

Authentication guards help control who can access parts of your Laravel app. They check if a user is logged in and allowed to see certain pages.

You want to protect admin pages so only admins can see them.
You need to allow users to log in with different methods, like web or API tokens.
You want to restrict access to certain routes based on user roles.
You want to keep guests from accessing user-only content.
You want to customize how users are authenticated in your app.
Syntax
Laravel
// Define guard in config/auth.php
'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],
    'api' => [
        'driver' => 'token',
        'provider' => 'users',
        'hash' => false,
    ],
],

// Use guard in routes or controllers
Route::middleware('auth:web')->group(function () {
    // Protected routes for web guard
});

// Check guard in code
if (Auth::guard('api')->check()) {
    // User is authenticated with api guard
}

Guards define how users are authenticated for each request.

Each guard uses a driver like 'session' or 'token' and a user provider.

Examples
This checks if a user is logged in using the default 'web' guard.
Laravel
// Using default web guard
if (Auth::check()) {
    // User is logged in
}
This checks if a user is authenticated using the 'api' guard.
Laravel
// Using api guard
if (Auth::guard('api')->check()) {
    // User is logged in via API token
}
This protects routes so only users authenticated by the 'admin' guard can access.
Laravel
// Protect routes with guard middleware
Route::middleware('auth:admin')->group(function () {
    // Routes only accessible by admin guard
});
Sample Program

This route checks if the user is logged in with the 'web' guard. If yes, it shows a welcome message. If not, it redirects to login.

Laravel
<?php

use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route;

// In routes/web.php
Route::get('/dashboard', function () {
    if (Auth::guard('web')->check()) {
        return 'Welcome to your dashboard!';
    }
    return redirect('/login');
});
OutputSuccess
Important Notes

Always define guards in config/auth.php before using them.

Use middleware auth:guardname to protect routes easily.

Guards can use different drivers like session, token, or custom drivers.

Summary

Authentication guards control how users log in and access your app.

Use guards to protect routes and check user login status.

Define guards in config and use them with middleware or code checks.