Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Priyanshi's avatar

Using auth and role middleware together

Hi, so I'm trying to redirect users according to the role of them to their dashboards. But when I login the page redirects back to the login page, and not the link it is supposed to go to. When I remove the auth middleware the page redirects but I get a 403 :user not logged in error. This is my code :

AuthContoller.php :

<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use App\Models\Login;
use App\Models\Signup;
use App\Models\User;
use App\Http\Controllers\Controller;

class AuthController extends Controller
{
    public function login(Request $request)
    {
        $credentials = $request->only('email', 'password');
        $role = $request->input('role');

        $guard = $this->getGuardByRole($role);

        if (!$guard) {
            return redirect()->route('login')->with('error', 'Invalid role');
        }

        Auth::shouldUse($guard);

        if (Auth::guard($guard)->attempt($credentials)) {
            // Authentication successful
            switch ($role) {
                case 'super admin':
                case 'admin':
                case 'additional admin':
                    // $role = auth()->user()->role;
                    return redirect()->route('admin');
                    break;
    
                case 'user':
                    // $role = auth()->user()->role;
                    return redirect()->route('user');
                    break;
            }
        }
// return view($viewName, ['userRole' => $userRole]);
        return redirect()->route('login')->with('error', 'Invalid login credentials');
    }

    protected function getGuardByRole($role)
    {
        switch ($role) {
            case 'user':
                return 'web';
            case 'super admin':
            case 'additional admin':
                return 'sadmin';
            case 'admin':
                return 'admin';
            default:
                // Handle default or unknown role
                return null;
        }
    }
}

web.php :

// user login page 
Route::get('login', function () {
    return view('commons.login');
});

Route::post('/login', [AuthController::class, 'login'])->name('login');

Route::middleware(['auth'])->group(function () {
Route::middleware(['role:super admin|admin|additional admin'])->group(function () {
    Route::get('admin/home', function () {
        return view('admin.home');
    })->name('admin');
   
});
Route::middleware(['role:user'])->group(function () {
    Route::get('user/home', function () {
        return view('user.home');
    })->name('user');
    
});
});

config/auth.php :

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

        // 'users' => [
        //     'driver' => 'database',
        //     'table' => 'users',
        // ],
        'admins' => [
            'driver' => 'eloquent',
            'model' => App\Models\Signup::class,
        ],
        'sadmins' => [
            'driver' => 'eloquent',
            'model' => App\Models\Login::class,
        ],
    ],


    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
        'admin' => [
            'driver' => 'session',
            'provider' => 'admins', // Use a custom 'admins' provider for the 'admin' guard
        ],
        'sadmin' => [
            'driver' => 'session',
            'provider' => 'sadmins', // Use a custom 'admins' provider for the 'admin' guard
        ],
    ],

kernel.php :

    protected $routeMiddleware = [
        'role' => \Spatie\Permission\Middlewares\RoleMiddleware::class,
        'permission' => \Spatie\Permission\Middlewares\PermissionMiddleware::class,
        'role_or_permission' => \Spatie\Permission\Middlewares\RoleOrPermissionMiddleware::class,
    ];


 protected $middlewareAliases = [
        'auth' => \App\Http\Middleware\Authenticate::class,

Please help

0 likes
22 replies
tisuchi's avatar

@priyanshi

Instead of:

Route::middleware(['role:super admin|admin|additional admin'])->group(function () {

Use:

Route::middleware(['role_or_permission:super admin|admin|additional admin'])->group(function () {
Priyanshi's avatar

The page admin/home or user/home gets loaded in the developer tools network tab but with a 302 found status after submitting the form, any ideas ?

Priyanshi's avatar

@krisi_gjika How can I check ? I mean pin point what middleware is causing this ? would using redirect in the AuthController be one of the reasons for redirection ?

I'm using it here :

if (Auth::guard($guard)->attempt($credentials)) {
            // Authentication successful
            switch ($role) {
                case 'super admin':
                case 'admin':
                case 'additional admin':
                    // $role = auth()->user()->role;
                    return redirect()->route('admin');
                    break;
    
                case 'user':
                    // $role = auth()->user()->role;
                    return redirect()->route('user');
                    break;
            }
        }
krisi_gjika's avatar

@Priyanshi assuming you are redirected to admin or user the login should be fine, however on those routes you have two middleware auth and role that you have not shared.

Priyanshi's avatar

@krisi_gjika The auth middleware is the of default laravel auth, and the role is from spatie

 protected $routeMiddleware = [
        'role' => \Spatie\Permission\Middlewares\RoleMiddleware::class,
        'permission' => \Spatie\Permission\Middlewares\PermissionMiddleware::class,
        'role_or_permission' => \Spatie\Permission\Middlewares\RoleOrPermissionMiddleware::class,
    ];

protected $middlewareAliases = [
        'auth' => \App\Http\Middleware\Authenticate::class,
Priyanshi's avatar

if i use the view function in AuthController.php, the data loads properly but the url stays /login i want the data to be outputted at admin/home or user/home not /login itself


        if (Auth::guard($guard)->attempt($credentials)) {
            // Authentication successful
            switch ($role) {
                case 'super admin':
                case 'admin':
                case 'additional admin':
                    // $role = auth()->user()->role;
                    return view('admin.home', compact('role'));
                    break;
    
                case 'user':
                    // $role = auth()->user()->role;
                    return view('user.home',compact('role'));
                    break;
            }
        }
Priyanshi's avatar

It is the 'auth' middleware which is causing the redirection. That means the user is being not authenticated i guess? any ideas ?

krisi_gjika's avatar

@Priyanshi your auth middleware is likely only checking your default guard, not the one you expect. Try passing the guards to the middleware:

Route::middleware(['auth:admin|sadmin', 'role:super admin|admin|additional admin'])
1 like
Priyanshi's avatar

@krisi_gjika This works, there's progress now the redirection is correct but i get Error : Auth guard [admin|sadmin] is not defined.

krisi_gjika's avatar

@Priyanshi try a comma separated list Route::middleware(['auth:admin,sadmin', 'role:super admin|admin|additional admin'])

RayC's avatar

Change @krisi_gjika code to this:

Route::middleware(['auth', 'role:super admin|admin|additional admin'])

This will check if they are logged in and if so, check they have the proper role to continue.

After looking a little more at your code, try this:

if (Auth::guard($guard)->attempt($credentials)) {
    if(Auth::user()->hasAnyRole(['super admin', 'admin', 'additional admin'])){
        return redirect()->route('admin');
    }elseif(Auth::user()->hasRole('user')) {
        return redirect()->route('user');
    }
}
Priyanshi's avatar

@RayC This rolls back to the original issue, no correct redirection. The auth middleware again causing the same problem. Thanks!

Priyanshi's avatar

@rayc If I do this :

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

        $guard = $this->getGuardByRole($role);

        if (!$guard) {
            return redirect()->route('login')->with('error', 'Invalid role');
        }

        Auth::shouldUse($guard);

        if (Auth::guard($guard)->attempt($credentials)) {
            // Authentication successful
            Log::info($guard);
            if(Auth::user()->hasAnyRole(['super admin', 'admin', 'additional admin'])){
                return redirect()->route('admin');
            }elseif(Auth::user()->hasRole('user')) {
                return redirect()->route('user');
            }
        }
// return view($viewName, ['userRole' => $userRole]);
        return redirect()->route('login')->with('error', 'Invalid login credentials');
    }

with this :

Route::middleware(['auth','role:super admin|admin|additional admin'])->group(function () {
    Route::get('admin/home', function () {
        return view('admin.home');
    })->name('admin');
   
});
Route::middleware(['auth','role:user'])->group(function () {
    Route::get('user/home', function () {
        return view('user.home');
    })->name('user');
    
});

it gives me the 'Invalid credentials error' but all my credentials are correct

krisi_gjika's avatar

@Priyanshi check what guard the auth middleware is using? did you dd() on that middleware? I can't help much without more information, and "it doesn't work" is not more information

Snapey's avatar

check your users actually have these roles in the model_has_roles table

Please or to participate in this conversation.