其他分享
首页 > 其他分享> > 验证失败后,FormRequest不填充$request-> old()

验证失败后,FormRequest不填充$request-> old()

作者:互联网

表单验证失败时,我的请求对象没有收到old()数据.我收到错误消息,但是没有旧的输入数据.

我已经阅读了有关类似问题的一些解决方案,这些解决方案参考了对控制器上的重定向进行更改的方法,但是由于重定向是由FormRequest类而不是Controller中下面引用的函数完成的,因此无法解决此问题.

还有其他人遇到过同样的问题吗?在阅读一些引用了现有错误的论坛时,我已经升级了实例,但是问题仍然存在.

任何帮助,将不胜感激.

版本:我已经在laravel 5.4、5.7和5.8上进行过尝试,但它们都没有呈现旧数据.

我如何进行请求验证
验证是通过扩展FormRequest的标准Requests文件完成的.

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class CustomerManagementRequest extends FormRequest {
    /**
     * 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 [
            'first_name' => 'required|min:2',
            'last_name' => 'required|min:2',
            'email' => 'required|min:4',
        ];
    }

}

我如何尝试访问视图中的旧数据:

value="{{old('first_name')}}"

重定向和验证在FormRequest中完成
重定向是通过Laravel标准的FormRequest类完成的.

protected function failedValidation(Validator $validator)
{
    throw (new ValidationException($validator))
                ->errorBag($this->errorBag)
                ->redirectTo($this->getRedirectUrl());
}

验证者响应:这是我进行上述功能检验时所看到的.它确实有我的表单数据.

Validator {#629 ▼
  #data: array:11 [▼
    "_token" => "1ynKXxi551UBGbJq6ftLsW6VsClZzmbZdHiHIxyt"
    "active_from_date" => "04/04/2019 10:58 PM"
    "last_sync_date" => "04/04/2019 11:00 PM"
    "first_name" => "Pizza"
    "last_name" => "Dough"
    "email" => null
    "full_phone" => null
    "phone" => null
  ]
}

在视图中输入old()参数将返回一个空数组
[]

解决方法:

验证之后,您应该检查所有验证是否通过.在控制器的方法中,您可以这样做,

$validator = Validator::make($request->all(), $rules);

if ($validator->fails()) {
    $messages = $validator->errors()->getMessages();
    return back()
           ->withErrors($messages)
           ->withInput();
}

希望这可以帮助 :)

标签:laravel,laravel-request,laravel-form,php
来源: https://codeday.me/bug/20191108/2005893.html