Laravel Livewire Bind Model Carbon Attribute

I'm using Laravel Livewire v2 and I need to bind a form date input to a model Carbon attribute in the backend Livewire component, but it seems to be impossible due date formatting.

To be more precise:

  • when selecting a date the form date input picker livewire make a api call sending the correct date (e.g.: 2020-02-02)
  • the Livewire component correctly receive and pass the string value to the model
  • the model cast the string to a Carbon object and assign it to its fillable attribute
  • the Livewire component try to send back to the client the data but it doesn't perform a ->format('Y-m-d') format on the Carbon object, so a serialized date object is sent
  • when object is unserialized fronted receive e.g. 2012-12-25T20:30:00.000000+04:00 MSK
  • the date input break

I also found that in Livewire v1 it was possible to cast properties (link) using key-value array or custom casting methods, but this has been removed in v2 (link); there is an example with hydrate/dehydrate methods to achieve the same effect but the example cover the case of a component property, not a nested one as in my case.

Is there a way to cast a model date prop or to add a format when sending data back to client?

1 Answer

Update (2020-10-15)

Since Livewire v2.3, Model Casting now works when binding to model attributes directly (aka wire:model).

All you need to do is go to your model and provide your date casting, lets take a Post model as an example:

class Post extends Model
{
    protected $casts = [
        'published_at' => 'date:Y-m-d'
    ];
}

This will let Livewire know that your published_at field should be serialized in the format Y-m-d to work with it client-side, and to convert it back into a Carbon (DateTime) instance whenever its updated.

Now, you can safely attach it to your <input> field:

<input type="date" wire:model="published_at" />
David Miller

David Miller

Executive Financial & Market Analyst

David Miller brings 15 years of experience in global economics, personal finance strategy, and market dynamics. He specializes in turning complex economic trends into actionable insights for everyday readers.