Laravel custom redirection after validation errors
Asked Answered
E

6

18

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.

Escalator answered 30/5, 2015 at 10:4 Comment(0)
E
9

Found a solutions. All I need to do is to override the initial response from

FormRequest.php

like such and it works like a charm.

public function response(array $errors)
{
    // Optionally, send a custom response on authorize failure 
    // (default is to just redirect to initial page with errors)
    // 
    // Can return a response, a view, a redirect, or whatever else

    if ($this->ajax() || $this->wantsJson())
    {
        return new JsonResponse($errors, 422);
    }
    return $this->redirector->to('login')
         ->withInput($this->except($this->dontFlash))
         ->withErrors($errors, $this->errorBag);
}
Escalator answered 30/5, 2015 at 12:22 Comment(1)
Great answer. The array parameter resembles the output of $errors = $validator->errors() in terms of structure (but the methods e.g. $errors->all() might not quite be used on it). So to get all the errors as an array, use the helper function array_flatten($errors)Salo
P
17

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";

    // ...
}
Pinkeye answered 28/11, 2016 at 0:58 Comment(3)
Actually is completely valid in L5.4Dowie
Still valid in L5.8Bismarck
"Missing required parameters for [Route: restaurant-update-images.user] [URI: panel/restaurant/update-images/{user}]." in Laravel 5.7 why?Scientist
S
12

If you do not want to use the validate method on the request, you may create a validator instance manually using the Validator facade. The make method on the facade generates a new validator instance: Refer to Laravel Validation

 public function store(Request $request)
   {
    $validator = Validator::make($request->all(), [
        'title' => 'required|unique:posts|max:255',
        'body' => 'required',
    ]);

    if ($validator->fails()) {
        return redirect('post/create')
                    ->withErrors($validator)
                    ->withInput();
    }

    // Store the blog post...
    }
Sycophancy answered 12/10, 2017 at 8:55 Comment(0)
E
9

Found a solutions. All I need to do is to override the initial response from

FormRequest.php

like such and it works like a charm.

public function response(array $errors)
{
    // Optionally, send a custom response on authorize failure 
    // (default is to just redirect to initial page with errors)
    // 
    // Can return a response, a view, a redirect, or whatever else

    if ($this->ajax() || $this->wantsJson())
    {
        return new JsonResponse($errors, 422);
    }
    return $this->redirector->to('login')
         ->withInput($this->except($this->dontFlash))
         ->withErrors($errors, $this->errorBag);
}
Escalator answered 30/5, 2015 at 12:22 Comment(1)
Great answer. The array parameter resembles the output of $errors = $validator->errors() in terms of structure (but the methods e.g. $errors->all() might not quite be used on it). So to get all the errors as an array, use the helper function array_flatten($errors)Salo
R
6

This works in Lara 7 Add an anchor to jump to the comment form if validation fails

protected function getRedirectUrl()
{
    return parent::getRedirectUrl() . '#comment-form';
}
Reopen answered 25/6, 2020 at 18:22 Comment(0)
W
4

If you are using the validate() method on the Controller

$this->validate($request, $rules);

then you can overwrite the buildFailedValidationResponse from the ValidatesRequests trait present on the base Controller you extend.

Something along this line:

protected function buildFailedValidationResponse(Request $request, array $errors)
{
    if ($request->expectsJson()) {
        return new JsonResponse($errors, 422);
    }

    return redirect()->route('login');
}
Windblown answered 8/6, 2017 at 21:27 Comment(0)
R
1

Variations on this answer have already been offered, but overriding the getRedirectUrl() method in a custom request can enable you to define the route parameters, rather than just the name that the $redirectRoute property offers.

Retinol answered 17/1, 2021 at 4:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.