Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm processing a form where a user can update their date of birth. The form gives the user 3 separate fields for day, month and year. On the server-side of course I want to treat these 3 separate fields as one value i.e. yyyy-mm-dd.

So before validation and updating my database, I want to alter the form request to create a date_of_birth field by concatenating year, month and day with - characters to create the date format I need (And possibly unset the original 3 fields).

Achieving this manually with my controller is not a problem. I can simply grab the input, join the fields together separated by - characters and unset them. I can then validate manually before passing off to a command to deal with the processing.

However, I would prefer to use a FormRequest to deal with the validation and have that injected into my controller method. Therefore I need a way of actually modifying the form request before validation is executed.

I did find the following question which is similar: Laravel 5 Request - altering data

It suggests overriding the all method on the form request to contain the logic for manipulating the data prior to validation.

<?php namespace AppHttpRequests;

class UpdateSettingsRequest extends Request {

    public function authorize()
    {
        return true;
    }

    public function rules()
    {
        return [];
    }

    public function all()
    {
        $data = parent::all();
        $data['date_of_birth'] = 'test';
        return $data;
    }

This is all well and good for the validation, but overriding the all method doesn't actually modify the data on the form request object. So when it comes to executing the command, the form request contains the original unmodified data. Unless I use the now overridden all method to pull the data out.

I'm looking for a more concrete way to modify the data within my form request that doesn't require the calling of a specific method.

Cheers

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
335 views
Welcome To Ask or Share your Answers For Others

1 Answer

in laravel 5.1 you can do that

<?php namespace AppHttpRequests;

class UpdateSettingsRequest extends Request {

public function authorize()
{
    return true;
}

public function rules()
{
    return [];
}

protected function getValidatorInstance()
{
    $data = $this->all();
    $data['date_of_birth'] = 'test';
    $this->getInputSource()->replace($data);

    /*modify data before send to validator*/

    return parent::getValidatorInstance();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...