noblemfd's avatar

How to display Access Denied if not Super Admin

I have this Controller:

class AdminLoginController extends Controller
{
    public function index() {
        return view('auth.admin.login');
    }
}

route\web

Route::get('/admin/login', 'Auth\AdminLoginController@index')->name('admin.login');

I am using spatie

How do I do it that if the logged in user is not 'Super Admin'

Auth::user()->hasRole('Super Admin')

The application should display Access Denied. But if its super admin, it should redirect to dashboard.

How do I get this done?

Thanks

0 likes
3 replies
tykus's avatar

Firstly, you can add a middleware to allow authorize only Super Admins using:

Route::get('/admin/login', 'Auth\AdminLoginController@index')
	->middleware('role:super-admin')
	->name('admin.login');

The Exception thrown by the package is an UnauthorizedException which you can see has a requiredRoles property. If you handle that exception in app/Exceptions/Handler.php, you can get the role from the Exception, and rethrow a new exception with your preferred message, e.g.

public function render(Throwable $e)
{
	if ($e instanceof \Spatie\Permission\Exceptions\UnauthorizedException) {
		throw new HttpException($e->getCode(), 'Access Denied');
	}

	parent::render($e);
}
noblemfd's avatar

@tykus

I am using spatie, and this is the way I have saved the super Admin into DB:

Super Admin

tykus's avatar
tykus
Best Answer
Level 104

In that case, change the middleware string middleware('role:Super Admin'), its just a string

Please or to participate in this conversation.