I understand how to bind dates to <input type="date">
(as of v2.3 of Laravel Livewire), by adding the cast date:Y-m-d
to a model's attribute. However, I can't find any information on whether it is similarly possible to bind a model's time attribute (i.e. an attribute with datatype of TIME) to <input type="time">
through a cast to datetime
(with some appropriate serialization format). Is this possible? Or has it not been implemented in Livewire as of yet?
I've experimented with a few different variations of casts and serialization formats myself, none have worked so far.
H:i
In the model, I cast the time attribute (in the database it has the time datatype, and it can be interpolated into blade templates fine using any of the options available to Carbon as usual) to datetime, with the format H:i
which is 24 hour time with leading zeroes as per the value usually required by <input type="time">
. [0]
The model's $casts
field looks like this:
protected $casts = [
'time' => 'datetime:H:i',
];
The view has this input
field:
<input type="time" wire:model="item.time" />
This does not work (the input remains blank).
I also tried this with the format set to H:i:s
, H-i
, H-i-s
, Hi
, His
, none of which work either.
Whoops! Seems I had simply forgotten to add a validation for the time attribute in the Livewire. By adding the rule:
public Item $item;
protected $rules = [
'item.time' => 'required|date_format:H:i',
];
and using either H:i
or H:i:s
for the format, the attribute was bound. This may have something to do with the way I validate my fields in this Livewire as well.
I suspect that in general any input with a value can be bound as long as the attribute is cast to the correct value.