简体   繁体   English

根据Laravel中的用户角色,对同一路径使用不同的控制器

[英]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.

相关问题 Laravel 5委托一条路由-根据角色加载不同的控制器 - Laravel 5 Entrust one route - load different controller based on Role 如何根据用户角色对同一路由使用不同的控制器? - How to use different controllers, depending on the user role, for the same route? 如何在Laravel中使用具有不同控制器功能和相同路径的不同形式 - How to use different form with different controller functions and the same route in Laravel Laravel同样的路线,不同的控制器 - Laravel same route, different controller Laravel不同路线相同控制器 - Laravel Different Route Same Controller 不同的控制器取决于用户角色 - Laravel 5.1 - Different controller depending on user role - Laravel 5.1 Laravel 为相同的资源路由调用不同的 controller - Laravel call different controller for same resource route Yii:根据用户角色使用其他范围 - Yii: Use a different scope based on user role 我如何在Laravel中将相同的路由用于两种不同的控制器功能方法 - how can i use same route for two different controller function methods in laravel 2个按钮使用Laravel在同一控制器中以相同的路径访问不同的方法 - 2 button accessing different method in the same controller with the same route using Laravel
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM