Laravel custom redirection after validation errors

Kenny Yap picture Kenny Yap · May 30, 2015 · Viewed 24.3k times · Source

Can I ask what have I done wrong in my LoginRequest.php where I've set a condition to redirect to a custom login page if there is any sort of error in the login process? I have my codes as below:

<?php namespace App\Http\Requests;

use App\Http\Requests\Request;

class LoginRequest extends Request
{

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

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
        'login_email'               =>  'required',
        'login_password'            =>  'required'
        ];
    }


    public function messages()
    {
        return [
            'login_email.required'          =>  'Email cannot be blank',
            'login_password.required'       =>  'Password cannot be blank'
        ];
    }

    public function redirect()
    {
        return redirect()->route('login');
    }
}

The code is supposed to redirect users who login from a nav bar login form to the main login page, if there are any errors, but it doesn't seem to redirect.

Answer

dokko picture dokko · Nov 28, 2016

if you want to redirect to a specific url, then use protected $redirect

class LoginRequest extends Request
{
    protected $redirect = "/login#form1";

    // ...
}

or if you want to redirect to a named route, then use $redirectRoute

class LoginRequest extends Request
{
    protected $redirectRoute = "session.login";

    // ...
}