Implementing Multi-Authentication with Guards in Laravel

Harish Kumar · · 1031 Views

This guide provides a detailed explanation of how to implement multi-authentication using guards in a Laravel application. This is useful for applications that need to support multiple user roles (e.g., admins, customers, employees) with different authentication requirements.

Understanding Guards in Laravel

What are Guards?
In Laravel, guards define how users are authenticated for each request. Laravel comes with a session guard which maintains the state of a user using session storage and cookies.

How Guards Work:
Guards work by using providers to retrieve users from the database. You can have multiple guards in an application, each configured to use a different provider and thus manage different types of users.

Setting Up Multi Authentication

Step-by-Step Configuration:

1. Create User Models:

  1. Create different models for each user type. For instance, Admin and Customer.

php artisan make:model Admin -m
php artisan make:model Customer -m

2. Migrate the Databases:

  1. Define schema for admins and customers tables in the migration files and run the migrations.

php artisan migrate

3. Modifying the Auth Configuration File:

  1. Open config/auth.php and add guards and providers for the new user types.

'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],
    'admin' => [
        'driver' => 'session',
        'provider' => 'admins',
    ],
    'customer' => [
        'driver' => 'session',
        'provider' => 'customers',
    ],
],

'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => App\Models\User::class,
    ],
    'admins' => [
        'driver' => 'eloquent',
        'model' => App\Models\Admin::class,
    ],
    'customers' => [
        'driver' => 'eloquent',
        'model' => App\Models\Customer::class,
    ],
],

4. Creating Middleware for Guards

Create middleware to handle authentication for different user types.

php artisan make:middleware AdminMiddleware
php artisan make:middleware CustomerMiddleware

In AdminMiddleware:

public function handle($request, Closure $next)
{
    if (!Auth::guard('admin')->check()) {
        return redirect('/login/admin');
    }

    return $next($request);
}

In CustomerMiddleware:

phpCopy codepublic function handle($request, Closure $next)
{
    if (!Auth::guard('customer')->check()) {
        return redirect('/login/customer');
    }

    return $next($request);
}

Register the middleware in app/Http/Kernel.php.

protected $routeMiddleware = [
    'admin' => \App\Http\Middleware\AdminMiddleware::class,
    'customer' => \App\Http\Middleware\CustomerMiddleware::class,
];

5. Implementing Controllers for Different User Types

Create authentication controllers for different user types.

php artisan make:controller AdminController
php artisan make:controller CustomerController

In AdminController:

public function login(Request $request)
{
    $credentials = $request->only('email', 'password');

    if (Auth::guard('admin')->attempt($credentials)) {
        return redirect()->intended('/admin/dashboard');
    }

    return back()->withErrors(['email' => 'Invalid credentials.']);
}

In CustomerController:

public function login(Request $request)
{
    $credentials = $request->only('email', 'password');

    if (Auth::guard('customer')->attempt($credentials)) {
        return redirect()->intended('/customer/dashboard');
    }

    return back()->withErrors(['email' => 'Invalid credentials.']);
}

6. Setting Up Routes

Define routes for different user types.

Route::prefix('admin')->group(function () {
    Route::get('login', [AdminController::class, 'showLoginForm']);
    Route::post('login', [AdminController::class, 'login']);
    Route::middleware('admin')->group(function () {
        Route::get('dashboard', [AdminController::class, 'dashboard']);
    });
});

Route::prefix('customer')->group(function () {
    Route::get('login', [CustomerController::class, 'showLoginForm']);
    Route::post('login', [CustomerController::class, 'login']);
    Route::middleware('customer')->group(function () {
        Route::get('dashboard', [CustomerController::class, 'dashboard']);
    });
});

Testing the Multi Authentication Setup

  1. Ensure you have forms for admin and customer logins.

  2. Test logging in as an admin and accessing admin routes.

  3. Test logging in as a customer and accessing customer routes.

  4. Verify that unauthenticated users are redirected appropriately.

Conclusion

By following this guide, you should be able to set up multi-authentication in a Laravel application using guards. This allows different user roles to have separate authentication processes and access controls, enhancing the security and organization of your application.

0

Please login or create new account to add your comment.

0 comments
You may also like:

Building a Real-Time Chat App with Laravel Reverb and Nuxt 3

Building a real-time chat application is a great way to understand the power of WebSockets and real-time communication. In this tutorial, we will walk through creating a Real-Time (...)
Harish Kumar

How to Set Up Nuxt 3 Authentication with Laravel Sanctum (Step-by-Step Guide)

In modern web development, securing your application’s authentication process is a top priority. For developers building Single Page Applications (SPA) or Server-Side Rendered (...)
Harish Kumar

Laracon US 2024: Laravel 11 Minor Features That Enhance Performance

At Laracon US 2024, Taylor Otwell and the Laravel team introduced a series of "minor" features for Laravel 11 that are anything but minor. These enhancements, while not headline-grabbing (...)
Harish Kumar

PHP OPCache: The Secret Weapon for Laravel Performance Boost

OPCache, a built-in PHP opcode cache, is a powerful tool for significantly improving Laravel application speed. This guide will demonstrate how to effectively utilize OPCache to (...)
Harish Kumar

How to Use DTOs for Cleaner Code in Laravel, Best Practices and Implementation Guide

When developing APIs in Laravel, ensuring your responses are clear, concise, and consistent is crucial for creating a maintainable and scalable application. One effective way to (...)
Harish Kumar

Data Type Validation in Laravel Collections with the `ensure()` Method

Before moving on to the ensure() method, let us first know what Laravel Collections actually are. These are wrappers of PHP arrays, offering a fluent and helpful interface in interacting (...)
Harish Kumar