Dol*_*rma 4 laravel laravel-5.6
在我的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);
}
}
Run Code Online (Sandbox Code Playgroud)
在我的溃逃中,我有这个路由组:
Route::group(['namespace' => 'Dashboard', 'middleware' => ['auth:web'], 'prefix' => 'dashboard'], function () {
$this->group(['prefix' => 'administrator'], function () {
$this->get('panel', 'AdminController@index');
});
Run Code Online (Sandbox Code Playgroud)
我的内核:
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
...
\App\Http\Middleware\CheckUserAdminRole::class,
];
Run Code Online (Sandbox Code Playgroud)
现在,当我将中间件添加CheckUserAdminRole到路由组时,例如以下代码:
Route::group(['namespace' => 'Dashboard', 'middleware' => ['auth:web','CheckUserAdminRole'], 'prefix' => 'dashboard'], function () {
Run Code Online (Sandbox Code Playgroud)
我收到此错误:
Class CheckUserAdminRole does not exist
Run Code Online (Sandbox Code Playgroud)
此代码无法解决我的问题:
php artisan route:clear
php artisan cache:clear
php artisan config:clear
composer dump-autoload
Run Code Online (Sandbox Code Playgroud)
您还可以轻松地将中间件和路由组一起使用,如下所示:
Route::group(['prefix' => 'admin', 'middleware' => 'auth'], function()
{
//All the routes that belongs to the group goes here
Route::get('dashboard', function() {} );
});
Run Code Online (Sandbox Code Playgroud)
不要将中间件注册到$middleware数组中,而应$routeMiddleware像这样注册它:
protected $routeMiddleware = [
...
'checkAdmin' => \App\Http\Middleware\CheckUserAdminRole::class,
];
Run Code Online (Sandbox Code Playgroud)
注意:在$middleware阵列中注册中间件会导致针对每个请求执行该中间件,因此不适用于特定路由。
然后,您可以在checkAdmin名称中使用它:
Route::group(['namespace' => 'Dashboard', 'middleware' => ['auth:web','checkAdmin'], 'prefix' => 'dashboard'], function () {
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7914 次 |
| 最近记录: |