在我的Web应用程序中,我有管理面板,我正在尝试通过此代码访问他们具有管理员角色的用户:
namespace App\Http\Middleware;
use Closure;
class CheckUserAdminRole
{
public function handle($request, Closure $next)
{
if (auth()->check()) {
if (auth()->check() && !auth()->user()->hasRole('admin')) {
auth()->logout();
return redirect(route('system.messages','userIsNotAdmin'));
}
}
return $next($request);
}
}
在我的溃败中我有这个路线组:
Route::group(['namespace' => 'Dashboard', 'middleware' => ['auth:web'], 'prefix' => 'dashboard'], function () {
$this->group(['prefix' => 'administrator'], function () {
$this->get('panel', 'AdminController@index');
});
我的内核:
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
...
\App\Http\Middleware\CheckUserAdminRole::class,
];
现在当我将我的中间件添加为CheckUserAdminRole
来路由组时,就像这段代码一样:
Route::group(['namespace' => 'Dashboard', 'middleware' => ['auth:web','CheckUserAdminRole'], 'prefix' => 'dashboard'], function () {
我收到此错误:
Class CheckUserAdminRole does not exist
这段代码无法解决我的问题:
php artisan route:clear
php artisan cache:clear
php artisan config:clear
composer dump-autoload
而不是在$middleware
数组中注册您的中间件,您应该在$routeMiddleware
中注册它,如下所示:
protected $routeMiddleware = [
...
'checkAdmin' => \App\Http\Middleware\CheckUserAdminRole::class,
];
注意:在qazxsw poi数组中注册中间件会导致它为每个请求执行,因此不适用于特定路由。
然后您可以使用$middleware
名称在路线中使用它:
checkAdmin
Route::group(['namespace' => 'Dashboard', 'middleware' => ['auth:web','checkAdmin'], 'prefix' => 'dashboard'], function () {
您也可以像这样轻松地使用中间件和路由组:
Source
您可以尝试使用前缀和组的中间件。
Route::group(['prefix' => 'admin', 'middleware' => 'auth'], function()
{
//All the routes that belongs to the group goes here
Route::get('dashboard', function() {} );
});
希望它的帮助