Notflip Notflip - 6 days ago 9
MySQL Question

Laravel mutate date before saving to database?

I have a date that's being selected in a datepicker in the following format

Y-m-d g:i A


So using AM/PM, it shows the following in my input field, which is correct

enter image description here

When I submit the form offcourse Laravel won't update the record because the format is unknown to my DATETIME field in mysql.

My 'date' field is added to the $dates array so it should be parsed by Laravel


I tried using a Mutator on my Model as following, without success


public function setDateAttribute($value)
{
$this->attributes['date'] = Carbon::createFromFormat('Y-m-d g:i A', $value)->format('Y-m-d H:i:s');
}


The original value is not being updated.
Any idea what I might be doing wrong?

Thank you

Answer

Laravel's date mutator expects a format like 'Y-m-d H:i:s', but you can use the $dateFormat attribute on your model to specify a different format. E.g.:

protected $dateFormat = 'Y-m-d g:i A';

Check out the Date Formats section in the docs under Date Mutators

Alternatively, you can parse the date using Carbon outside of the model, because attributes listed in the $dates will also accept Carbon instances:

$model->date = Carbon::createFromFormat('Y-m-d g:i A', '2016-11-29 02:00 PM');

This is the approach I typically use. To me this feels more like a front-end concern where you're trying to map a user-friendly format to one your models/DB expects, so I'll usually put this logic into a controller.

Comments