mazhar07's avatar

Multi user authentication system in Laravel 11

Hello everyone! I'm trying to create a multi-user authentication system in Laravel 11 manually using multiple guards, where each user will use their own login page and an unauthenticated user will redirect to their respective login page. Any suggestions will be appreciated. Thanks.

0 likes
7 replies
LaryAI's avatar
Level 58

To create a multi-user authentication system in Laravel 11 with multiple guards, you'll need to follow these steps:

  1. Define the guards in your config/auth.php file.
  2. Create the necessary controllers for each type of user.
  3. Set up the middleware to redirect unauthenticated users to the correct login page.
  4. Create the authentication routes for each guard.
  5. Set up the views for each login page.

Here's a step-by-step guide:

Step 1: Define Guards

In your config/auth.php, define the guards for your different user types. For example, if you have admin and user, you might have:

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

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

    // ...
],

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

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

    // ...
],

Step 2: Create Controllers

Create controllers for each type of user. For example, AdminAuthController and UserAuthController. In each controller, you'll handle the login and logout functionality for that guard.

Step 3: Middleware for Redirects

You may need to create middleware that checks if a user is authenticated with a specific guard and redirects them to the correct login page if they are not. Here's an example middleware for an admin guard:

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;

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

        return $next($request);
    }
}

Register this middleware in your app/Http/Kernel.php.

Step 4: Authentication Routes

Define routes for each type of user. For example:

// User authentication routes
Route::get('login', 'UserAuthController@showLoginForm')->name('login');
Route::post('login', 'UserAuthController@login');
Route::post('logout', 'UserAuthController@logout')->name('logout');

// Admin authentication routes
Route::prefix('admin')->name('admin.')->group(function () {
    Route::get('login', 'AdminAuthController@showLoginForm')->name('login');
    Route::post('login', 'AdminAuthController@login');
    Route::post('logout', 'AdminAuthController@logout')->name('logout');
});

Step 5: Create Views

Create separate login views for each type of user. For example, resources/views/auth/login.blade.php for users and resources/views/admin/login.blade.php for admins.

Step 6: Update Unauthenticated Method

In your app/Exceptions/Handler.php, update the unauthenticated method to redirect users based on the guard:

protected function unauthenticated($request, AuthenticationException $exception)
{
    if ($request->expectsJson()) {
        return response()->json(['message' => $exception->getMessage()], 401);
    }

    $guard = Arr::get($exception->guards(), 0);
    switch ($guard) {
        case 'admin':
            $login = 'admin.login';
            break;
        default:
            $login = 'login';
            break;
    }

    return redirect()->guest(route($login));
}

Make sure to import the necessary classes at the top of your Handler.php file:

use Illuminate\Auth\AuthenticationException;
use Illuminate\Support\Arr;

With these steps, you should have a multi-user authentication system in place with Laravel 11. Each user type will have its own login page, and unauthenticated users will be redirected to the correct login page based on the guard they are attempting to access.

hsumudupriya's avatar

@LaryAI How are the sessions of admins and users managed? Are both sessions managed using a single table or are two tables needed to separately manage the sessions of admins and users? If it needs two tables to separately manage the sessions of admins and users, how do we do that?

Tray2's avatar

Yes.

  1. Use a single login page.
  2. Use the users table.
  3. Use roles for the different kinds of users.
1 like
Jayaat's avatar

@Tray2 sir how can i able to redirect after successful login on the basis of roles provided inside user table like im using ajax to send request after getting success i want to redirect them their respective page(for starters their dashboards and also not other infiltrate inside each dashboards ) how can i proceed futher? as other example shows to add middleware inside kernel.php but by default i dont have any kind of file and i dont know where to add middleware as well

Tray2's avatar

@Jayaat Please don't highjack other peoples threads, create your own, that way it's way more likely you will get help.

Snapey's avatar

where each user will use their own login page

Well thats a first ! I wonder why noone else has done that...

Oh, of course, I have just realised, no one does that because until they are logged in, everyone is a guest and you cannot tell them apart.

1 like

Please or to participate in this conversation.