Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Form Request Add Custom Variable After Validation

This is my form request code, i want to add new variable after validation success, so i can access that variable at my controller :

class CouponRequest extends Request
{
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'start_year' => 'required',
            'start_month' => 'required',
            'start_day' => 'required',
            'start_time' => 'required',
            'finish_year' => 'required',
            'finish_month' => 'required',
            'finish_day' => 'required',
            'finish_time' => 'required',
        ];
    }

    public function afterValidation()
    {
        $this->start_date = Carbon::create( $this->start_year, $this->start_month, $this->start_day );
    }
}

So after validation has no error, i can call this instance at my controller :

$request->start_date;

Could i do this?

like image 629
Yudi Yohanes Septian Gotama Avatar asked Aug 03 '16 08:08

Yudi Yohanes Septian Gotama


1 Answers

All above methods work but IMO I would override the passedValidation method in the form request class. This method is called after the validation checks are passed and hence keep the data clean.

Ex.

public function passedValidation()
{
    $this->merge([
       'start_date' => Carbon::create( $this->start_year, $this->start_month, $this->start_day )
    ]));
}

If you dump the data now you should see your new start_date value as well.

like image 176
ChinwalPrasad Avatar answered Sep 28 '22 03:09

ChinwalPrasad