SaroBeatbox
SaroBeatbox

Reputation: 63

Custom Message - Laravel 7 - Denied Authorization

I have a controller in which in its function it verifies the policy assigned to the Post model :

App\Http\Controllers\PostController

class PostController extends Controller
{
    public function index(Request $request, Post $post) {
        
 $response = Gate::inspect('viewAny', $post);

    if ($response->allowed()) {
        echo 'valid';
    } else {
        echo 'invalid';
    }
    }
}

File : PostPolicy

 public function viewAny(User $user)
 {
    return $user->role === 'admin' ? Response::allow() : Response::deny();
 }

when the user is logged in as admin, it returns the message of logged in admin, when it is not admin it returns a 403 response, I would like to replace this 403 response with a message like 'User is not administrator'

Upvotes: 0

Views: 814

Answers (1)

Ma Kobi
Ma Kobi

Reputation: 896

You can use can() and cant() methods on the user model in your controller:

if ($user->cant('view-any', $post)) {
    return 'User is not administrator';
}

Source: Laravel Docs - Authorization

Upvotes: 1

Related Questions