在 Laravel 5.5 中验证之前更改 $request 的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46615292/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 16:45:44  来源:igfitidea点击:

change value of $request before validation in laravel 5.5

laravellaravel-validationlaravel-5.5

提问by Maria

I have a form in route('users.create').

我在route('users.create').

I send form data to this function in its contoller:

我在其控制器中将表单数据发送到此函数:

public function store(UserRequest $request)
{

    return redirect(route('users.create'));
}

for validation I create a class in

为了验证,我创建了一个类

App\Http\Requests\Panel\Users\UserRequest;

App\Http\Requests\Panel\Users\UserRequest;

class UserRequest extends FormRequest
{
    public function rules()
    {
        if($this->method() == 'POST') {
             return [
                 'first_name' => 'required|max:250',

It works.

有用。

But How can I change first_namevalue before validation (and before save in DB)?

但是如何first_name在验证之前(以及保存在数据库中之前)更改值?

(Also with failed validation, I want to see new data in old('first_name')

(同样验证失败,我想在 old('first_name')

Update

更新

I try this:

我试试这个:

 public function rules()
    {
     $input = $this->all();


     $input['first_name'] = 'Mr '.$request->first_name;
     $this->replace($input);

     if($this->method() == 'POST') {

It works before if($this->method() == 'POST') {But It has not effect for validation or for old()function

以前可以用if($this->method() == 'POST') {但是对验证或old()功能没有影响

回答by numbnut

Override the prepareForValidation()method of the FormRequest.

覆盖 的prepareForValidation()方法FormRequest

So in App\Http\Requests\Panel\Users\UserRequest:

所以在App\Http\Requests\Panel\Users\UserRequest

protected function prepareForValidation()
{
    if ($this->has('first_name'))
        $this->merge(['first_name'=>'Mr '.$this->first_name]);
}

回答by Webdesigner

Why not doing the validation in the controller? Than you can change things before you validate it and doing your db stuff afterward.

为什么不在控制器中进行验证?比您可以在验证之前更改内容并在之后进行数据库操作。

public function store(Request $request)
{
    $request->first_name = 'Mr '.$request->first_name;

    Validator::make($request->all(), [
        'first_name' => 'required|max:250',
    ])->validate();

    // ToDo save to DB

    return redirect(route('users.create'));
}

See also https://laravel.com/docs/5.5/validation

另见https://laravel.com/docs/5.5/validation