如何创建可以通过 laravel 的 1 个或多个角色访问的中间件
how to create middleware that can access by 1 or more role with laravel
我有这样的自定义中间件
那么这是我的路线
我要
Route::post('facility', 'FacilityController@store')
->name('facility.store')
->middleware(['superAdmin', 'admin', 'tenantRelation', 'receptionist']);
这4个角色都可以访问,但总是失败。
谁能帮帮我?谢谢
您将一个中间件堆叠在另一个中间件之上,因此请求从一个中间件传递到另一个中间件,如果发生任何故障,请求将不会被进一步处理。
您需要创建另一个中间件来检查用户是否属于任何给定角色。
php artisan make:middleware RestrictedAccess
在中间件的 handle 方法中你可以做
public function handle($request, Closure $next)
{
$role_ids = [1, 2, 3, 4];
if (! in_array(auth()->user()->roleId, $role_ids)) {
abort('403');
}
return $next($request);
}
并将中间件添加到 App\Http\Kernel.php
文件的
protected $routeMiddleware = [
...
'auth.restricted_access' => \App\Http\Middleware\RestrictedAccess::class,
...
];
那么你可以将你的路线修改为
Route::post('facility', 'FacilityController@store')
->name('facility.store')
->middleware('auth.restricted_access');
我有这样的自定义中间件
那么这是我的路线
我要
Route::post('facility', 'FacilityController@store')
->name('facility.store')
->middleware(['superAdmin', 'admin', 'tenantRelation', 'receptionist']);
这4个角色都可以访问,但总是失败。
谁能帮帮我?谢谢
您将一个中间件堆叠在另一个中间件之上,因此请求从一个中间件传递到另一个中间件,如果发生任何故障,请求将不会被进一步处理。
您需要创建另一个中间件来检查用户是否属于任何给定角色。
php artisan make:middleware RestrictedAccess
在中间件的 handle 方法中你可以做
public function handle($request, Closure $next)
{
$role_ids = [1, 2, 3, 4];
if (! in_array(auth()->user()->roleId, $role_ids)) {
abort('403');
}
return $next($request);
}
并将中间件添加到 App\Http\Kernel.php
文件的
protected $routeMiddleware = [
...
'auth.restricted_access' => \App\Http\Middleware\RestrictedAccess::class,
...
];
那么你可以将你的路线修改为
Route::post('facility', 'FacilityController@store')
->name('facility.store')
->middleware('auth.restricted_access');