我有 3 个用户角色,超级管理员、管理员和用户或访客,3 组路由
1 = 将角色分配给用户(超级管理员(。
2 = 管理面板(超级管理员,管理员(。
3 = 索引页(超级管理员、管理员、用户或来宾(。
这三组路由由具有给定权限的用户访问。我尝试了很多方法,但没有一个有效
用户模型
public function role(){
return $this->belongsToMany('AppRole','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('AppRole','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')
});
中间件.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);
您只需获取用户的所有角色并检查他是否已授予权限即可:
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)
}