Laravel Form Request(s) Handling Redirects after Validation

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

Sometimes you may want to have some login to determine where the user gets redirected to after submitting a form. Form Requests give a variety of ways.

By default there are 3 variables declared in the Request $redirect, $redirectRoute and $redirectAction.

On top of those 3 variables you can override the main redirect handler getRedirectUrl().

A sample request is given below explaining what you can do.

<?php namespace App;

use Illuminate\Foundation\Http\FormRequest as Request;

class SampleRequest extends Request {

    // Redirect to the given url
    public $redirect;

    // Redirect to a given route
    public $redirectRoute;

    // Redirect to a given action
    public $redirectAction;


    /**
     * Get the URL to redirect to on a validation error.
     *
     * @return string
     */
    protected function getRedirectUrl()
    {

        // If no path is given for `url()` it will return a new instance of `Illuminate\Routing\UrlGenerator`

        // If your form is down the page for example you can redirect to a hash
        return url()->previous() . '#contact';

        //`url()` provides several methods you can chain such as

        // Get the current URL
        return url()->current();

        // Get the full URL of the current request
        return url()->full();

        // Go back
        return url()->previous();

        // Or just redirect back
        return redirect()->back();
    }


    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [];
    }

    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }
}


Got any Laravel Question?