在我的网络应用程序中,我有管理员面板,并且我试图通过此代码访问他们具有管理员角色的用户:
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
答案 0 :(得分:3)
您应该在$middleware
中注册中间件,而不是在$routeMiddleware
数组中注册您的中间件:
protected $routeMiddleware = [
...
'checkAdmin' => \App\Http\Middleware\CheckUserAdminRole::class,
];
注意:在$middleware
数组中注册middlware会导致执行每个请求,因此不适用于特定路由。
然后您可以在checkAdmin
名称的路线中使用它:
Route::group(['namespace' => 'Dashboard', 'middleware' => ['auth:web','checkAdmin'], 'prefix' => 'dashboard'], function () {
答案 1 :(得分:3)
这是一个简单的修复程序,无需触摸Kernel
文件并利用Policy
。 accessAdmin
是在Policy
文件中创建的函数。
Route::group(['namespace' => 'Dashboard', 'middleware' => 'can:accessAdmin, App\User', 'prefix' => 'dashboard'], function () {
$this->group(['prefix' => 'administrator'], function () {
$this->get('panel', 'AdminController@index');
});
答案 2 :(得分:1)
您还可以像这样轻松地一起使用中间件和路由组:
Route::group(['prefix' => 'admin', 'middleware' => 'auth'], function()
{
//All the routes that belongs to the group goes here
Route::get('dashboard', function() {} );
});
答案 3 :(得分:0)
您可以尝试使用带前缀和组的中间件。
Route::middleware(['Auth'])->prefix('api/')->group(function() {
Route::group(['prefix' => 'review/'], function () {
Route::get('/', 'User\Controllers\Api\UserController@getUserReviews');
});
});
希望它能提供帮助