我有3个用户角色,SuperAdmin,Admin和User或guest,3组路由
1 =将角色分配给用户(SuperAdmin)。
2 =管理面板(SuperAdmin,管理员)。
3 =索引页面(SuperAdmin,Admin,User或Guest)。
这三组路由是具有指定权限的用户访问。我尝试了很多东西,但都没用
用户模型
public function role(){
return $this->belongsToMany('App\Role','role_assigns');
}
public function hasRole($role)
{
if ($this->role()->where('name','=',$role)->first()){
return true;
}return false;
}
public function isSuperAdmin() {
return $this->role()->where('name', '=','superadmin')->exists();
}
public function isAdmin() {
return $this->role()->where('name', '=','admin')->exists();
}
public function isUser() {
return $this->role()->where('name', '=','user')->exists();
}
角色模型
public function user(){
return $this->belongsToMany('App\Role','role_assigns');
}
路线
Route::group(['middleware' => 'roles:superadmin'], function (){
// User Assiginign Routes
Route::get('/users', 'UserRoleController@showAllUser');
Route::get('/assign', 'UserRoleController@showRoleAndUser');
Route::post('/user/{user_id} /role/{role_id}','UserRoleController@assignRoleToUser');
Route::post('assign_role/user/{user_id}/role/{role_id}',[
'uses'=>'UserRoleController@assignRoleToUser',
'as'=>'assign_role'
]);
Route::post('/ar', 'UserRoleController@showAllUser');
});
Route::group(['middleware' => 'roles:admin,superadmin'], function () {
// Product Dashboard for Admin
Route::get('/', 'ProductController@index');
Route::post('add_product','ProductController@store');
Route::get('/edit/{id}','ProductController@edit');
Route::get('/delete/{id}','ProductController@destroy');
Route::post('/update_product/{id}','ProductController@update');
Route::get('/add_product', function () {
return view('content.add_product');
});
});
Route::group(['middleware' => 'roles:admin,superadmin,user'], function () {
Route::get('/index', 'ProductController@index_page')
});
Middleware.php
public function handle($request, Closure $next, ... $roles)
{
if (!Auth::check())
return redirect('signin');
$user = Auth::user();
if ( $user->isSuperAdmin()) {
return $next($request);
}elseif ($user->isAdmin() ){
return $next($request);
}
elseif ($user->isUser()||$request->user()->hasRole($roles)==null){
return redirect('index');
}
return response('Not Auttroize insufficent end of page',401);
答案 0 :(得分:2)
您可以简单地通过获得用户的所有角色并检查其是否具有权限来完成此操作:
Route::group(['middleware' => 'roles:admin,superadmin,user'], function () {
Route::get('/index', 'ProductController@index_page')
});
然后在中间件中应该做
public function handle($request, Closure $next, string $roles)
{
$user_roles = Auth::user()->role;
$roles = explode(',' $roles);
if ($user_roles->whereIn('role', $roles)->count()) {
return $next($request);
}
throw new Exeception('Unauthorized', 401)
}