不同的控制器取决于用户角色 - Laravel 5.1

时间:2016-01-04 10:27:51

标签: php laravel laravel-5.1

我不确定这是好事还是坏事,但我正在尝试根据用户角色使用不同的控制器/方法加载相同的路由。

尝试像下面那样进行一些角色过滤,但不确定这是否可行:

Route::group(['before' => 'role:admin'], function() {
   Route::get('/', 'FirstController@index');
});

Route::group(['before' => 'role:editor'], function() {
   Route::get('/', 'SecondController@index');
});


Route::filter('role', function($route, $request, $value) {
   // what to do here and is this the right way?
});

但是我没有让它发挥作用。我怎么能做到这一点?

修改

找到此主题:Laravel same route, different controller

但接受的答案是:

if( ! Auth::check())

始终在routes.php中返回false

1 个答案:

答案 0 :(得分:0)

也许你可以沿着这些方向做点什么?

Route::group(['middlware' => ['web', 'auth']], function (Router $router)
{
    /** get the logged in user here **/
    Auth::loginUsingId(2);
    $user = Auth::user();

    //you can move this to some other function but just to get the idea out i did it this way.
    if ($user->hasRole('admin'))
    {
        $router->get('test', function ()
        {
            dd('admin');
        });
    }
    elseif ($user->hasRole('owner'))
    {
        $router->get('test', function ()
        {
            dd('owner');
        });
    }
});