Step 1
create a middleware for role checking logic
~$ php artisan make:middleware RoleChecker
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');
}
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,
];
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']);
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)
Thanks for the solution.
And you can use the spread operator to make it more simple and clean :
and test on the $authorizedRoles array .