Laravel 验证错误后的自定义重定向

Laravel custom redirection after validation errors

请问我在 LoginRequest.php 中设置了一个条件,如果登录过程中出现任何错误则重定向到自定义登录页面,我做错了什么?我的代码如下:

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

如果有任何错误,该代码应该将从导航栏登录表单登录的用户重定向到主登录页面,但它似乎没有重定向。

已找到解决方案。我需要做的就是覆盖

的初始响应

FormRequest.php

像这样,它就像一个魅力。

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

如果您想重定向到特定的 url,请使用 protected $redirect

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

    // ...
}

或者如果你想重定向到命名路由,则使用 $redirectRoute

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

    // ...
}

如果您在 Controller

上使用 validate() 方法
$this->validate($request, $rules);

然后你可以覆盖ValidatesRequests你扩展的基础Controller上的特征buildFailedValidationResponse

沿着这条线的东西:

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

    return redirect()->route('login');
}

如果您不想在请求中使用验证方法,您可以使用 Validator facade 手动创建一个验证器实例。 facade上的make方法生成一个新的validator实例:参考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...
    }

这适用于 Lara 7 验证失败添加锚点跳转到评论表单

protected function getRedirectUrl()
{
    return parent::getRedirectUrl() . '#comment-form';
}

已经提供了这个答案的变体,但是覆盖 custom request 中的 getRedirectUrl() 方法可以让您定义路由参数,而不仅仅是 $redirectRoute 属性 个报价。