Implementing Multi-Authentication with Guards in Laravel

Harish Kumar · · 511 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:

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

PHP Generators: Efficient Data Handling and Iteration Techniques

PHP Generators offer a powerful and memory-efficient way to handle large datasets and complex iteration scenarios in your applications. They provide a more elegant solution compared (...)
Harish Kumar

Compress and Download Files in Laravel Using ZipArchive with Examples

In web development, file compression is essential for optimizing data transfer and storage. Laravel provides tools for creating and downloading compressed files. This guide explores (...)
Harish Kumar

Building Real-Time Chat Applications with Laravel Reverb and Vue 3

Real-time chat applications are increasingly important for seamless communication and instant connectivity. Laravel Reverb and Vue.js 3 provide developers with the tools to create (...)
Harish Kumar

Laravel Facades: Simplifying Code and Improve Readability

As an integral part of Laravel, a renowned PHP framework, Facades provide a static interface to classes stored in the application's service container. They serve as static proxies (...)
Harish Kumar