Return a custom Unauthorized page for Laravel Form Requests

By JacobBennett

By default, when using a Laravel Form Request, you have a handy option to authorize the request before passing it along to validate against your set of rules. As expected, if false is returned from the authorize method, you will receive a 403 response status code. The problem with the response that Laravel provides is that it skips right past your App\Exceptions\Handler and instead is caught in the Illuminate\Routing\Route class. What this means is that any custom error pages that you might be returning from your Handler class for a 403 / Unauthorized Request are ignored.

A quick fix to this is to override the forbiddenResponse method by placing the following method on your abstract App\Http\Requests class.

public function forbiddenResponse()
{
    return abort(403);
}

This will ensure that any Form Requests that are not authorized will follow the typical flow through your App\Exceptions\Handler class and will return your custom error pages, assuming you have them set up as defined in the Custom Error Pages Docs.

Created 1 year ago | Updated 1 year ago

Comments