DEV Community

Md. Imrul Hasan
Md. Imrul Hasan

Posted on

How to create your own middleware for User Role in Laravel without using a package?

Step 1

create a middleware for role checking logic

~$ php artisan make:middleware RoleChecker
Enter fullscreen mode Exit fullscreen mode

Step 2

Middlewere/RoleChecker.php

public function handle($request, Closure $next, $super_adminRole, $adminRole,  $sellerRole)
{
    $roles = Auth::check() ? Auth::user()->role->pluck('name')->toArray() : [];

    if (in_array($super_adminRole, $roles)) {
        return $next($request);
    } else if (in_array($adminRole, $roles)) {
        return $next($request);
    } else if (in_array($sellerRole, $roles)) {
        return $next($request);
    }

    return Redirect::route('home');
}
Enter fullscreen mode Exit fullscreen mode

In the above code we assume that there are 4 types of users. Super Admin, Admin, Seller and Normal Auth User. We don't need to check the normal users in the middleware. So we are checking the remaining three Roles.

Step 3

Kernel.php

protected $routeMiddleware = [
    'roleChecker' => \App\Http\Middleware\RoleChecker::class,
];
Enter fullscreen mode Exit fullscreen mode

Here we added the middleware

Step 4

web.php

middleware(['roleChecker:super_admin,admin,seller']);
middleware(['roleChecker:super_admin,null,null']);
middleware(['roleChecker:null,admin,null']);
middleware(['roleChecker:null,null,seller']);

Enter fullscreen mode Exit fullscreen mode

Use any of above code snippet to set middleware on any Route

Note

  • When you set null to any of these three roles, it means, that role is restricted. So if middleware(['roleChecker:null,null,seller']);, Then only seller can access...

Thanks... Share...

Top comments (1)

Collapse
 
farouk2u profile image
FAROUK BLALOU

Thanks for the solution.

And you can use the spread operator to make it more simple and clean :

public function handle($request, Closure $next, ...$authorizedRoles) {

}
Enter fullscreen mode Exit fullscreen mode

and test on the $authorizedRoles array .