简体   繁体   中英

Laravel replace validation value not showing in validated() array

In my blade form, I have an input field that asks for a hour value, lets say input_stage_hour

I am trying to convert this to minutes AFTER validation, but BEFORE it hits my controller... In my form request im using the passedValidation method to convert hours to minutes, then in my controller i am filling my model using $request->validated()

The problem is, it is passing through the original value and not the converted value.

My cut down form request is below;

public function rules()
{
    return [
        'input_stage_hour' => ['required', 'numeric', 'integer'],
    ];
}

protected function passedValidation()
{
    $this->replace([
        'input_stage_hour' => intval($this->input_stage_hour) * 60,
    ]);
}

If I pass a value like 2 into the input_stage_hour and then dd($request->validated()) in my controller, it still shows the value 2 instead of 120

The data that comes from that validated method on the FormRequest is coming from the Validator not the FormRequest itself. So if you really wanted to do this with the FormRequest and be able to call that validated method you would have to adjust the data the Validator is holding or adjust the validated method.

Example attempting to adjust the data the Validator is holding:

protected function passedValidation()
{
    $data = $this->validator->getData();

    $this->validator->setData(
        ['input_stage_hour' => $data['input_stage_hour'] * 60] + $data
    );
}

If you wanted to override the validated method:

public function validated()
{
    $data = parent::validated();

    return ['input_stage_hour' => $data['input_stage_hour'] * 60] + $data;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM