admins unable to access the admin dashboard laravel 8

Viewed 259

I am using policies to prevent users from accessing the admin panel. Only admins can be able to access the admin panel. I have created the policies and registered them in the authservice provider. The problem is when an admin logins in they are still not able to view the admin panel and instead, they return the 403 pages. where have I gone wrong?

the route in the web.php

Route::group(['prefix'=>'admin','middleware'=>(['auth','can::acessAdmins'])],function(){
        Route::resource('dashboard',AdminDashboard_Controller::class); 
}

the helper functions in the user model

public function hasAnyRoles($roles){
   return $this->roles()->wherein('Role_name',$roles)
    ->first()?true:false;
}
public function hasRole($role){
   return $this->roles()->wherein('Role_name',$role)
   ->first()?true:false;
}

Admin access policy

public function accessAdmins(user $user){
   return $user->hasAnyRoles(['SuperAdmin','NormalAdmin']);
}
public function manageAdmins(user $user){
  return $user->hasAnyRoles(['SuperAdmin']);
}
1 Answers

You should change the route to this:

Route::group(['prefix'=>'admin','middleware'=>(['auth','can:accessAdmins'])],function(){
        Route::resource('dashboard',AdminDashboard_Controller::class); 
}

The can::accessAdmins to can:accessAdmins, multiple typos.

Also see https://laravel.com/docs/8.x/middleware#middleware-parameters for more information on parameters.

And besides that you should make sure that the authorized user has the right roles.

Related