Return view with custom status code in Laravel 5

There are times when you want to render a view, but pass along a custom status code. This is not reflected in the official laravel documentation. You need to set the status code with the setStatusCode() method.

In the following example, am returning a view and passing a 403 status code. Following works with Laravel 5.2


return response()->view('myviewname')->setStatusCode(403);

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);
    }
}