0

I am getting date from user on Laravel application from three different selects i.e. dd(1-31) mm(1-12) yyyy(1905-2016)

How do I convert it to php date and insert it into mysql column created by Laravel migrations using fol code:

$table->date('dateOfBirth')->nullable();

also, i want to validate the date using Laravel validator after composing it.

Eirtaza
  • 137
  • 2
  • 16
  • are you using jquery or javascript? try to fill a hidden field with these three values together and send it as an unique date. Doing that you can use a custom form request to validate the field by its name, check the [docs](https://laravel.com/docs/5.2/validation#form-request-validation). – Rafael Berro Jun 13 '16 at 18:25

2 Answers2

2

If it's separate inputs (Input::get('month'), Input::get('day'), Input::get('year')), then you can just put it together as a string:

$date = Input::get('year')."-".Input::get('month')."-".Input::get('day');

You can also use Carbon to create it:

$date = Carbon::createFromDate(Input::get('year'),Input::get('month'), Input::get('day'));

Carbon will help you validate that the format is correct.

aynber
  • 22,380
  • 8
  • 50
  • 63
1

Let's say you are posting you data to this controller:

class MyController
{
    ....
    public function store(Request $request)
    {
        //validate
        $this->validate($request, [
            'day' => 'required|integer|min:1|max:31',
            'month' => 'required|integer|min:1|max:12',
            'year' => 'required|integer|min:1905|max:'.date('Y'),
        ]);

        //parse
        $day = $request->input('day');
        $month = $request->input('month');
        $year = $request->input('year');

        $dateOfBirth = \Carbon\Carbon::createFromDate($year,$month,$day);

        //persist
        if($dateOfBirth) {
            $model = new Model();
            $model->dateOfBirth = $dateOfBirth->toDateString();
            ...
            $model->save();
        } else {
            echo "Problem parsing date";
        }
    }
}

My opinio here is that you should use a calendar component to avoid problems like February "30".

Felippe Duarte
  • 14,901
  • 2
  • 25
  • 29