Redirect all Laravel 5 FormRequest Authorize Failures to a Route/URL

Form validation and other checks have become very easy to implement in Laravel 5 with the help of Form Requests.

Every Form Request should have an authorize() and a rules() method.

You can do ownership and other access checks in the authorize() method, and in the rules() method, you return an array with the rules for form validation. By default, if the method authorize fails/returns false, Laravel sends a 403 forbidden response.

Instead of that, when the authorize fails, you can redirect to an error page with a custom error message.

<?php namespace App\Http\Requests;

use App\Post;

class PostFormRequest extends Request {

    protected $post;
    protected $error;

    /**
     * Check if post belongs to user
     */
    public function authorize()
    {
        $this->post = Post::findOrFail($this->input('id', 0); //default ID to 0, if not sent through form.
        if ($this->user->id !== $this->post->user_id) {
             $this->error = 'Sorry, you do not have permission to edit this post';
             return false;
        }
        return true;
    }
    /**
     * This method will be invoked if authorize() fails
     */
    public function forbiddenResponse()
    {
        return redirect('error')->with('error_message', $this->error);
    }
    /**
     * Validation rules
     */
    public function rules()
    {
        return [
            'title' => 'required',
            'content' => 'required'
        ];
    }
}

With the above code, if a request fails the authorize() method, it’ll be redirected to www.domain.com/error with an error message.

However, if you have multiple Form Requests, its better to put all the code in the parent Request (app/Http/Requests/Request.php) class.

<?php namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

abstract class Request extends FormRequest {
    //A generic error message, can be overridden in the sub class
    protected $error = 'An error occurred';

    public function forbiddenResponse()
    {
        return redirect('dashboard')->with('msg_error', $this->error);
    }
}

2 thoughts on “Redirect all Laravel 5 FormRequest Authorize Failures to a Route/URL”

  1. This actually helped me a ton, thank you!

    Please note you have a small typo in the second snippet, in line ‘user Illuminate\Foundation\Http\FormRequest;’

    Thanks again!

Leave a Reply to Andreas Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.