[英]Use different controller for same route based on user role in Laravel
What I want is I can use different controller for same route based on logged in user's role, so if user logged in with role of admin I want controller for given url is loaded from Admin namespace. 我想要的是我可以根据登录用户的角色为同一路径使用不同的控制器,因此如果用户使用admin角色登录,我希望控制器为给定的URL从Admin命名空间加载。 I've done like this
我这样做了
Route::group(['middleware'=>['install','auth']],function(){
$role = \Auth::user()->role;
switch ($role)
{
case 'admin':
$prefix = 'Admin\\';
break;
case 'Foo':
$prefix = 'Foo\\';
break;
}
Route::resource('/foo',$prefix.'FooController');
//.......
But is says that Auth::user() is null, is there another approach to do this? 但是据说Auth :: user()为null,还有另一种方法可以做到这一点吗?
尝试使用auth()->user()
或包含特定的Auth
模块而不是\\Auth::user()
这可能是因为解释器使用的是错误的Auth
模块,因为其中有很多。
You can do a redirect using middleware for either the admin or the 'Foo', just check the auth role and return a redirect, to the correct route. 您可以使用中间件为管理员或“ Foo”进行重定向,只需检查auth角色,然后将重定向返回正确的路由即可。
class AdminOnly
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if(Auth::user()->role != 'admin'){
return redirect('path/to/non/admin/route');
}
return $next($request);
}
}
Then define both routes in your routes file and use the middleware to redirect between them. 然后在路由文件中定义两个路由,并使用中间件在它们之间重定向。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.