Home Ask Login Register

Developers Planet

Your answer is one click away!

ozzii February 2016

Laravel 5.1 Modify input before form request validation

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't seem to work.

When I set $this->start_dt input field to 2016-02-06 12:00:00 and $this->end_dt to 2016-02-06 13:00:00 I still get validation error "end_dt must be after start_dt". Which means the input request values aren't getting changed when you update $this->start_dt and $this->end_dt inside the rules() function.

public function rules()
{
    if ($this->start_dt){
        $this->start_dt = Carbon::createFromFormat('d M Y H:i:s', $this->start_dt . ' ' . $this->start_hr . ':'. $this->start_min . ':00');
    }

    if ($this->end_dt){
        $this->end_dt = Carbon::createFromFormat('d M Y H:i:s', $this->end_dt . ' ' . $this->end_hr . ':'. $this->end_min . ':00');
    }

    return [
        'start_dt' => 'required|date|after:yesterday',
        'end_dt' => 'required|date|after:start_dt|before:' . Carbon::parse($this->start_dt)->addDays(30)            
    ];
}

Note: start_dt and end_dt are date picker fields and the start_hr, start_min are drop down fields. Hence I need to create a datetime by combining all the fields so that I can compare.

Answers


user2094178 February 2016

You can do something like the following:

public function rules(Request $request)
{
    if ($request->has('start_dt')){
        $request->replace('start_dt', Carbon::createFromFormat('d M Y H:i:s', $request->start_dt . ' ' . $request->start_hr . ':'. $request->start_min . ':00'));
    }

    if ($request->has('end_dt')){
         $request->replace('end_dt' ,Carbon::createFromFormat('d M Y H:i:s', $request->end_dt . ' ' . $request->end_hr . ':'. $request->end_min . ':00'));
    }

    return [
        'start_dt' => 'required|date|after:yesterday',
        'end_dt' => 'required|date|after:start_dt|before:' . Carbon::parse($request->start_dt)->addDays(30)            
    ];
}

Post Status

Asked in February 2016
Viewed 3,436 times
Voted 14
Answered 1 times

Search




Leave an answer


Quote of the day: live life