6

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?

5 Answers5

6

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.

ChinwalPrasad
  • 181
  • 1
  • 9
3

In your form request use function prepareForValidation()

protected function prepareForValidation(): void
{
    $this->merge([
        'start_date' => Carbon::now()
    ]);
}

Cheers!

Maik Lowrey
  • 10,972
  • 4
  • 14
  • 43
Adam Kozlowski
  • 4,952
  • 2
  • 31
  • 44
2

You could do this

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

public function validate()
{
    parent::validate();

    $this->afterValidation();
}

And then access the attribute in your controller as

$request->get('start_date');
Jari Pekkala
  • 757
  • 6
  • 8
0

I made the validation in the Controller. The method has a "Request $request" parameter. I have a I do this:

$input = $request->all();
$input['my_new_field] = 'the_data';
Jesús Amieiro
  • 2,285
  • 20
  • 15
0

I am using this method after success request for manipulations.

Source: 50116187/1101038

public function withValidator(Validator $validator)
{
    if ( $validator->fails() ) {

        \Log::info('Error! No Manipulation!');

    }else{

        $this->merge([
            'custom' => 'Test Manipulation!'
        ]);

        \Log::info('Success Manipulation!');
    }

}
ahmeti
  • 295
  • 4
  • 9