在路由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
?
答案 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');
});