Dwight Watson's blog

Handling forbidden form requests in Laravel 5

This blog post was originally published a little while ago. Please consider that it may no longer be relevant or even accurate.

By default, the FormRequest will simply throw a 403 Forbidden response if the authorize() method returns false. This could happen for a number of reasons, for example; the user is logged out or the user doesn't have access to the resource they're trying to interact with. Unfortunately, the default 403 response isn't lovely.

/**
* Get the response for a forbidden operation.
*
* @return \Illuminate\Http\Response
*/
public function forbiddenResponse()
{
return new Response('Forbidden', 403);
}

Often you'll want to adjust this response to make it a little more friendly for your users. It's actually really easy, especially as you're given a base Request object out of the box for you to extend. Simply override this forbiddenResponse() method with whatever you need, like a redirect to a login page.

<?php namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

abstract class Request extends FormRequest
{
/**
* Get the response for a forbidden operation.
*
* @return \Illuminate\Http\Response
*/
public function forbiddenResponse()
{
return $this->redirector->route('login');
}
}

A blog about Laravel & Rails by Dwight Watson;

Picture of Dwight Watson

Follow me on Twitter, or GitHub.