Laravel 5.6通过用户参数分配路线

时间:2018-08-01 11:20:33

标签: php laravel authentication laravel-5 routes

在路由app/routes/web.php中,我有一个带有一堆资源路由的组:

Route::group(['middleware' => 'auth'], function()
{
   Route::get('/points', 'PagesController@points');
   Route::get('/users', 'PagesController@users');
   Route::get('/users/groups', 'PagesController@user_groups');
   Route::resource('point', 'PointController');
   Route::resource('user', 'UserController');
   Route::resource('users/group', 'UserGroupController');
});

Auth::routes();

Route::get('/logout', 'Auth\LoginController@logout')->name('logout');

现在我想通过用户参数在该组中分配路由:

use App\UserGroup;

$access = UserGroup::find( auth()->user()->group_id )->access;

Route::group(['middleware' => 'auth'], function()
{
   if ($access == 1) {
      Route::get('/points', 'PagesController@points');
      Route::get('/users', 'PagesController@users');
      Route::get('/users/groups', 'PagesController@user_groups');
      Route::resource('point', 'PointController');
      Route::resource('user', 'UserController');
      Route::resource('users/group', 'UserGroupController');
   }
});

但是我无法在Route::group中获得用户参数,因为发生了错误:Trying to get property 'group_id' of non-object

如何在中间件之前在auth()->user()->group_id中获得app/routes/web.php

2 个答案:

答案 0 :(得分:1)

在回调中使用$ access参数

$access = UserGroup::find( auth()->user()->group_id )->access

Route::group(['middleware' => 'auth'], function() use ($access)
{
   if ($access == 1) {
      Route::get('/points', 'PagesController@points');
      Route::get('/users', 'PagesController@users');
      Route::get('/users/groups', 'PagesController@user_groups');
      Route::resource('point', 'PointController');
      Route::resource('user', 'UserController');
      Route::resource('users/group', 'UserGroupController');
   }
});

答案 1 :(得分:1)

您可以create中间件'GroupAccess'。然后是assign it to alias,即

'groupAccess' => \App\Http\Middleware\GroupAccess::class

最后在它的handle方法中检查您的状况

public function handle($request, Closure $next)
{
    if (UserGroup::find( auth()->user()->group_id )->access === 1)
        return $next($request);
    else
        return back();
}

然后只需在路由组中指定此中间件

Route::group(['middleware' => ['auth','groupAccess']], function()
{
      Route::get('/points', 'PagesController@points');
      Route::get('/users', 'PagesController@users');
      Route::get('/users/groups', 'PagesController@user_groups');
      Route::resource('point', 'PointController');
      Route::resource('user', 'UserController');
      Route::resource('users/group', 'UserGroupController');
});