I think you may direct checking the current authenticated user something like this auth()->user()->isAdmin() instead passing parameter for checking...
Jun 10, 2021
5
Level 5
Pass multiple roles in controller construct to middleware
I have a role based middleware like below,
public function handle(Request $request, Closure $next, $role)
{
if (! $request->user()->hasRole($role)) {
abort(401, 'This action is unauthorized.');
}
return $next($request);
}
and User.php
public function authorizeRoles($roles)
{
if ($this->hasAnyRole($roles)) {
return true;
}
abort(401, 'This action is unauthorized.');
}
public function hasAnyRole($roles)
{
if (is_array($roles)) {
foreach ($roles as $role) {
if ($this->hasRole($role)) {
return true;
}
}
} else {
if ($this->hasRole($roles)) {
return true;
}
}
return false;
}
public function hasRole($role)
{
if ($this->roles()->where('name', $role)->first()) {
return true;
}
return false;
}
Now in controller i have added like below,
$this->middleware('CheckRole:Admin');
Now i want add another role permission for same midleware like below,
$this->middleware('CheckRole:Admin,JournalAdmin');
but it taking only first parameter which is Admin.
i tried to add like below in web group too.
Route::group([ "middleware" => "CheckRole:Admin,JournalAdmin"], function() {
Route::get('dashboard',[AdminDashboardController::class,'getAdminDashboard']);
});
But it is not working. if user has any one role which matches the middleware parameter then it should allow, please help me
Level 75
public function handle(Request $request, Closure $next, ...$roles)
{
// now you have $roles as an array
}
Please or to participate in this conversation.