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

jjudge's avatar

Handling date attributes after submitting a form

An eloquent model can be given a list of attributes that are dates:

// MyModel
protected $dates = ['dob', 'start_date', 'date_for_foo'];

When model instances are fetched from the database, these dates are automatically converted to Carbon objects, which is handy. No getter is required to do that conversion. Those Carbon objects can then easily be formatted for use in display and in forms.

Now the problem comes when binding a model to a form. When the form containing say dog is submitted, it will contain the dob as a string. This may be YYYY-MM-DD or DD-MM-YYYY or some other format, all depending on the requirements of the system. Passing that to the model to save gives errors:

// MyModel
public function update()
{
    // Validate etc.
    // Does not work - it expects Carbon to be passed in, with gives an eloquent error
    // when saving the submitted string "YYYY-MM-DD" or "DD-MM-YYYY".
    $my_model->update(Input::only(['dob']));
}

That is kind of understandable, because parsing a date will need some details about how it should be parsed (e.g. is it US, or UK format?) so eloquent does not want to make any assumptions here. I work around this with a mutator:

// MyModel bound to the form with a DOB picker
public function setDobAttribute($value)
{
    if (! $value instanceof Carbon) {
        $value = Carbon::parse($value); // Parse according to what formats we expect from the user.
    }
    // Now we are giving the model a Carbon object, which it is expecting.
    $this->attributes['dob'] = $value;
}

That works, but I have the hunch that it is unnecessary. Do I need to do this, or should using the $dates property do this for me automatically, meaning that I am possibly doing something else wrong? Or is this always needed, with the $dates property feature not really designed for forms in the first place? Is there maybe a property I should be setting on the model to tell eloquent how to parse data strings? Or a callback/event of some type that could be set up as a general handler for ALL date attributes without the need to create a mutator for each one?

0 likes
1 reply
jjudge's avatar

Maybe there is some other level where the conversion from a submitted "dob" string to a Carbon object happens? Probably not middleware, since it is too specific to a model.

Please or to participate in this conversation.