2

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']);
}
James Z
  • 12,209
  • 10
  • 24
  • 44
  • You can use Laravel Permission This package allows you to manage user permissions and roles in a database. https://github.com/spatie/laravel-permission – ORHAN ERDAY Jul 07 '21 at 13:04

1 Answers1

0

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.

frogeyedman
  • 534
  • 1
  • 5
  • 23