Search code examples
laravelauthenticationrolesuser-roleslaravel-authentication

How Can I Assign 2 Or More User Roles To 1 One Route In Laravel?


I have user table with column role for user roles with Enum value:

Migration

$table->enum('role', ['Admin','author','editor']);

What I want is, only Admin and author user Can Access to site.com/view/problems this page.

I have created 3 Middlewares on \app\http\Middleware with this content.

public function handle($request, Closure $next)
{
    if ($request->user() && $request->user()->role != 'Admin') {
        return new Response(view('unauthorized')->with('role', 'Admin'));
    }

    return $next($request);
}

and put them into Kernal.php

protected $routeMiddleware = [
        'Admin' =>\App\Http\Middleware\AdminMiddleware::class,
        'author' =>\App\Http\Middleware\authorAdminMiddleware::class,
        'editor' =>\App\Http\Middleware\editorAdminMiddleware::class,
    ];

then used them in web.php like this

Route::get('/view/problems', function () {
    //
})->middleware('Admin', 'editor');

But when I logged in with Admin user, It says you can access this page with author user.

And when I logged in with author user, it says you can access this page with admin user.

I want when I logged in with Admin or author user role, Can access this page. And when I logged in with editor can't access this page.

I have used Middleware Groups too. And it looks like before.

How can I do that ?


Solution

  • When you pass in multiple middlewares in the middleware() function, it requires that all the middlewares be run and passed. Now if the user does not have both the roles, it will fail.

    One thing you could do is define a new Middleware which checks if the user is author or editor and lets it pass like

    public function handle($request, Closure $next)
        {
            if ($request->user() && $request->user()->role != 'Admin' && $request->user()->role != 'author') {
                return new Response(view('unauthorized')->with('role', 'Admin'));
            }
            return $next($request);
        }
    

    Another thing you can do is look into permissions i.e. assign particular permissions to both the roles. Say CanViewProblemsPermission and assign it to both the roles. You will require to implement that on your own or use a library like this