Override response to authorize method returning false in FormRequest
I'm working on an API for my project and I'm trying to have some consistency across all responses so that they all contain a 'status' key. Currently the only response that doesn't have this is when a request fails in the authorize() method of my FormRequest.
The response given my the exception only contains 'message'. Is there a way to throw a custom response to include the structure that I want?
You can override thefailedAuthorization method in the FormRequest class throwing your own custom exception, and generate your own response in that renderable exception class.
Or, you can handle the Illuminate\Auth\Access\AuthorizationException in the App\Exceptions\Handlers class
In render method of app/Exceptions/Handler.php add
use Illuminate\Auth\Access\AuthorizationException;
public function render($request, Throwable $exception)
{
if ($exception instanceof AuthorizationException ) {
// your response
}
return parent::render($request, $exception);
}