Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

jdavidbakr's avatar

Using Carbon::Parse() for date values in model

I have a form that I'd like to allow the user to enter values that will be parsed by Carbon::Parse(). The fields are validating fine as dates. My model has several date fields in it, and right now I'm doing the following to perform the update:

$fields = $request->all();
if(!empty($fields['date1'])) {
  $fields['date1'] = Carbon::parse($fields['date1']);
}
...
$model->save($fields);

This to me seems very inefficient and I feel like the Eloquent model should be able to handle this with just a simple:

$model->save($request->all());

but if the dates aren't formatted in YYYY-MM-DD then it fails, even though it passes the date validation.

I was thinking maybe the best plan would be to do something like this in the model:

public function setDate1Attribute($value) {
  $this->attributes['date1'] = Carbon::parse($value);
}

Alternatively I thought about overriding Model::asDateTime() and replacing the Carbon::createWithFormat() call with Carbon::parse().

Any thoughts on this? Are these the best methods, or is there an ever more efficient way?

Thanks!

0 likes
4 replies
helmerdavila's avatar

If your date1 its only a date field.

class Yourmodel extends Model {
    protected $dates = ['date_1'];
    //yes, an array, and you can add deleted_at field after maybe
}

I suggest use Carbon::createFromFormat

$model->date_1 = Carbon\Carbon::createFromFormat('d/m/Y', $fields['date1'])->format('Y-m-d');
$model->save();
// the d/m/Y its supposed, can be d-m-Y, etc.
phildawson's avatar
Level 26

I was thinking maybe the best plan would be to do something like this in the model:

Yes to this

jdavidbakr's avatar

@helmerdavila - that was my original plan but I wanted to simplify it and allow for $model->update($request->all()) instead of having to manually convert the dates everywhere I'm setting it.

@phildawson - thanks for the confirmation - that is what I ended up doing and it is working well.

Snapey's avatar

I came across this snippet today when reading the 5.0 to 5.1 upgrade notes

Date Formatting

Previously, the storage format for Eloquent date fields could be modified by overriding the getDateFormat method on your model. This is still possible; however, for convenience you may simply specify a $dateFormat property on the model instead of overriding the method.

does this help?

Please or to participate in this conversation.