Hi folks,
I am trying to bind a Carbon property to the default HTML date picker input field. And I can not get it working without a workaround. Has anybody ideas to make it better? I found a lot of posts regarding a similar issue. But this always includes having a Carbon property on a Eloquent Model. They use a model cast to circumvent that. But I don't won't to bind a Model property. I have a property directly in my Livewire class.
Here my class:
class WorkloadList extends Component
{
public Carbon $date;
public function mount()
{
$this->date = Carbon::createMidnightDate();
}
public function render()
{
return view('workload');
}
}
My view:
<input type="date" wire:model.debounce="date">
My problem is, that the input field isn't populated with the date on load. It shows 'yy-mm-dd' as a placeholder. And when I change the date in the input, I get these error on the update:
TypeError
Cannot assign string to property App\Http\Livewire\Workload\WorkloadList::$date of type Carbon
It's clear to me, that a proper cast to string is missing. But how can I get that? I also tried DateTime type instead of Carbon. It's the same issue.
Here is my current workaround. But that feels ugly and clunky.
class WorkloadList extends Component
{
public string $dateString;
public CarbonImmutable $dateObject;
public function mount()
{
$this->dateObject = CarbonImmutable::createMidnightDate();
$this->dateString = $this->dateObject->toDateString();
}
public function updatedDateString($value)
{
$this->dateObject = CarbonImmutable::createFromFormat('Y-m-d', $value);
}
public function render()
{
return view('workload');
}
}
<input type="date" wire:model.debounce="dateString">
Best,
Arne