Skip to content

Instantly share code, notes, and snippets.

@JacobBennett
Last active December 21, 2015 21:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JacobBennett/05b7e4f9142bda44cabe to your computer and use it in GitHub Desktop.
Save JacobBennett/05b7e4f9142bda44cabe to your computer and use it in GitHub Desktop.
Return a custom Unauthorized page for Laravel Form Requests

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.

published: true
preview: When authorizing an action using Laravel Form Requests, any failure returns an immediate 403. Let's see how we can implement a custom error page.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment