You should always have return $next($request);
at the end of a middleware file... Some of these examples fail to do that.
Here's how your routes will be (web.php file):
Route::middleware('auth')->group(function () {
Route::middleware('CheckRole:super-admin')->group(function () {
//super-admin only routes here
});
Route::middleware('CheckRole:user')->group(function () {
//user only routes here
});
});
To add more roles to the above code, just put CheckRole:super-admin,user
you can keep going with commas for the specific group.
The middlewares below will automatically keep anyone without permission out of the areas specified above, and only when a user is logged in
Make sure to add the below middleware to:
App\Http\Kernel.php
Under
protected $middlewareAliases = [
Put the following line:
'CheckRole' => \App\Http\Middleware\CheckRole::class,
Your middleware will be:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Symfony\Component\HttpFoundation\Response;
class CheckRole
{
/**
* Handle an incoming request.
*
* @param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next
*/
public function handle(Request $request, Closure $next, ...$roles): Response
{
if ($request->user()) {
$userRole = Auth::user()->role->value('name');
if (! in_array($userRole, $roles)) {
abort(403, 'Your account permissions do not allow access to the requested page');
}
}
return $next($request);
}
}
This assumes you only have 1 role for 1 user. If you have multiple roles for 1 user, that would be a different check in your middleware code
If you have multiple Roles for multiple Users, you can use this middleware:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Symfony\Component\HttpFoundation\Response;
class CheckRole
{
/**
* Handle an incoming request.
*
* @param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next
*/
public function handle(Request $request, Closure $next, ...$roles): Response
{
if ($request->user()) {
$userRoles = Auth::user()->roles
->pluck('name')
->toArray();
if (! array_intersect($userRoles, $roles)) {
abort(403, 'Your account permissions do not allow access to the requested page');
}
}
return $next($request);
}
}