I have added the Saptie Laravel Permission Package in a Laravel 5.8 API application. Every works fine and I get exception when a non admin user tries to access admin specific routes.
However the default exception is rendered as HTML 403 User does not have the right roles
. Considering I am using this inside an API application, I would like to return my own custom message for such exceptions.
I tried checking if the auth()->user()->hasRole('admin')
but still got the same default exception page. Here's my code
route
Route::post('products', 'ProductController@store')->middleware('role:super-admin|admin'); // create a new product
Controller method
if (auth()->user()->hasRole('admin')) {
// create & store the product
$product = Product::create($request->all())
// return new product
$responseMessage = 'Successful operation';
$responseStatus = 200;
$productResource = new ProductResource($product);
return response()->json([
'responseMessage' => $responseMessage,
'responseStatus' => $responseStatus,
'product' => $productResource
]);
} else {
return response()->json([
'responseMessage' => 'You do not have required authorization.',
'responseStatus' => 403,
]);
}
Why is my custom message not showing?