我想通过auth:admin中间件预先检查两个不同的路由组。这对于内部的第一个路由组非常适用,但对另一个命名空间中的第二个路由组则不适用。
“我的路线”文件如下所示:
Route::group(['middleware' => ['auth:admin']], function(){
Route::group(['prefix' => 'admin', 'namespace' => 'Admin', 'as' => 'admin.'], function(){
Route::resource('dashboard', 'DashboardController')->only(['index', 'create', 'store']);
});
Route::group(['prefix' => 'team/{team_id}', 'namespace' => 'Team', 'as' => 'team.'], function(){
Route::resource('dashboard', 'DashboardController')->only(['index', 'create', 'store']);
});
});
如果我没有登录并尝试去admin / dashboard,我将被重定向到login / admin。但是,如果我尝试转到team / 1 / dashboard,则会显示错误“尝试获取非对象的属性”标头”。 我怎样才能使auth:admin中间件也与我的团队路线一起使用?
答案 0 :(得分:0)
创建一个middleware
class IsAdmin
{
public function handle($request, Closure $next)
{
if (Auth::user()->permission == 'admin') {
return $next($request);
}
return redirect()->route('some.route'); // If user is not an admin.
}
}
注册kernel.php
protected $routeMiddleware = [
....
'is.admin' => \App\Http\Middleware\IsAdmin::class,
];
所以您的路线:
Route::group(['middleware' => 'is.admin'], function () {
Route::group(['prefix' => 'admin', 'namespace' => 'Admin', 'as' => 'admin.'], function(){
Route::resource('dashboard', 'DashboardController')->only(['index', 'create', 'store']);
});
Route::group(['prefix' => 'team/{team_id}', 'namespace' => 'Team', 'as' => 'team.'], function(){
Route::resource('dashboard', 'DashboardController')->only(['index', 'create', 'store']);
});
});