Add route middleware in bootstrap/app.php
$app->routeMiddleware([
'auth' => App\Http\Middleware\Authenticate::class,
'role' => App\Http\Middleware\Role::class,
]);
To middleware to routes within a group,
Use “,” separate roles, don’t use “|” as separater, the tutorial from here https://docs.spatie.be/laravel-permission/v3/basic-usage/middleware/ is for Laravel only
$router->group(['middleware' => 'role:administrator,super-admin'], function () use ($router) {
$router->get('/version', function () use ($router) {
// Uses Role Middleware
return $router->app->version();
});
});
Create a Role Middleware in App\Http\Middleware folder.
…$roles in the handler function can accept multiple roles
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
use Spatie\Permission\Exceptions\UnauthorizedException;
class Role
{
/**
* Role MiddleWare handle function
*
* @param [type] $request
* @param Closure $next
* @param [type] ...$roles
* @return void
*/
public function handle($request, Closure $next, ...$roles)
{
if (Auth::guest()) {
throw UnauthorizedException::notLoggedIn();
}
/**
* Check User Roles by laravel-permission
* Or by your own way
* @example https://docs.spatie.be/laravel-permission/v3/basic-usage/role-permissions/ Using permissions via roles
*/
if (!Auth::user()->hasAnyRole($roles)) {
throw UnauthorizedException::forRoles($roles);
}
return $next($request);
}
}