我正在尝试将普通用户重定向到首页,并将管理员重定向到仪表板。在我的用户表中,我有一个名为 role 的列。一个用户具有 admin 作为角色值,而另一个用户具有 NULL 。
这是我的AdminMiddleware:
public function handle($request, Closure $next)
{
if (Auth::user()->role != 'admin') {
return redirect('/home');
} else {
return $next($request);
}
这是我的LoginController:
protected function redirectTo(){
if (Auth::user()->role != 'admin') {
return 'home';
} else {
return 'dashboard';
}
也设置了内核:
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
'admin' => \App\Http\Middleware\AdminMiddleware::class,
];
最后,这是路线:
Auth::routes();
Route::get('/', 'HomeController@index')->name('home');
Route::get('/home', 'HomeController@index')->name('home');
Route::get('/movies/create', 'HomeController@create')->name('create');
Route::post('/home', 'HomeController@store')->name('store');
Route::group(['middleware' => ['auth', 'admin']], function(){
Route::get('/dashboard', function(){
return view('admin.dashboard');
});
});
登录时,无论我是以admin作为角色值的用户身份登录还是以NULL作为角色值的用户身份登录,都将重定向到我的主页。但是,如果我尝试“手动”访问仪表板,则通过在浏览器中编写url,只有具有admin作为角色值的用户才能获得访问权限,因此这部分效果很好。问题是,如果我以具有管理员角色值的用户身份登录,则不会重定向到仪表板。我似乎在这里没有发现任何错误。有人知道线索在哪里吗?