Laravel 5.1 Modify input before form request validation

后端 未结 5 949
感情败类
感情败类 2020-12-20 21:05

Is there a way to modify input fields inside a form request class before the validation takes place?

I want to modify some input date fields as follows but it doesn

5条回答
  •  旧时难觅i
    2020-12-20 21:36

    Try these steps:

    1- Middleware

    first of all you should create a middleware in app/Http/Middleware:

     'toGregorian',
            'created_at' => 'toDateTime',
        ];
    
        protected function transform($key, $value)
        {
            if (!array_key_exists($key, $this->fields)) {
                return $value;
            }
    
            $function = $this->fields[$key];
    
            return call_user_func($function, $value);
        }
    }
    

    with this middleware you can define fields that you want to manipulate them before calling validation and call a specific function to manipulate them.

    note: i defined toGregorian and toDateTime in my own helper functions. you can handle it with your own functions

    2- Kernel

    then modify Http/Kernel.php like bellow:

    protected $middlewareGroups = [
        'web' => [
            ...
    
            \App\Http\Middleware\EnglishStrings::class,
        ],
    
        'api' => [
            ...
        ],
    ];
    

提交回复
热议问题