0

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'

  • 1
    Have a look at [policy responses](https://laravel.com/docs/7.x/authorization#policy-responses). – Remul Sep 01 '20 at 11:28
  • i'm using laravel translation – Alzafan Christian Sep 01 '20 at 11:33
  • when i change to `return $user->role === 'admins' ? Response::allow() : Response::deny('User is not administrator');` return a page 403 with the message User is not administrator , but i wanna return for example a false , and on the controller if the response is false , so i'll will do something . – SaroBeatbox Sep 01 '20 at 11:38
  • you can use abort_if(!$user->can('viewAny', Model::class), Response::HTTP_FORBIDDEN, 'response message'); – Alzafan Christian Sep 01 '20 at 12:01

1 Answers1

1

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

Ma Kobi
  • 888
  • 6
  • 21