Questions & Answers

Override Authorizable can method in Laravel

I've recently inherited this quite new Laravel project (it was 8, I've since upgraded to 9), and they use $request->user()?->can('some_permission') a lot of places. But they also have a user_level property on the user that is either 100 for admin or 0 for normal user (don't ask why they've set it as a number, I have no clue). So the admin users don't get any permissions set, which means that they of course get false for any can() check. Is there a way to override the can() method to return true if user_level is set to 100? Or is there another way to have admin users always get all available permissions?

Answers(1) :

I think you can take advantage of a Policy's before() method. If you want to check something, before is run first (if it is present in the Policy) and if it returns true, it will automatically allow.

In your example, I think it should be:

public function before(User $user, $ability)
    if ($user->user_level >= 100) {
        return true;