Working with dates

What seems to be the problem:
When casting to a date property and error occurs when trying to addYear(). The exact message states: "Call to a member function addYear() on string"

Steps to Reproduce:
Have a input type of date, change the date field and the error is thrown.

Are you using the latest version of Livewire:

Do you have any screenshots or code examples:

public $endsOnDate;
public $reminder;

protected $casts = [
    'endsOnDate' => 'date:Y-m-d',
    'reminder' => 'date:Y-m-d',

public function mount()
    $this->reminder = now();
    $this->endsOnDate = now()->addYear();

public function updatedReminder()
    $this->endsOnDate = $this->reminder->addYear();

public function render()
    return view('livewire.testing');

The view looks like this:

   <input wire:model="reminder" type="date" />
   <input wire:model="endsOnDate" type="date" />

The end goal is to add a year to the endsOnDate when the reminder date is updated. How can I do this?

I think what’s happening is that livewire needs to cast $reminder and endsOnDate as a javascript readable format so upon roundtrip, they’re posting back as strings and aren’t being recast as dates. I don’t think recasting the datatypes happens on the update lifecycle. You may have to attach your logic to the hydrate() method or manually recast $endOnDate as a Carbon instance and do the addYear() then if you want to do the work at the updated lifecycle. Both should work.

Okay, I went and tried to implement and was getting errors at the hydrate() method. For more explicit behavior, I’d stick with the updatedReminder() method as you had before but cast and addYear() on the subsequent Carbon instance.

public function updatedReminder()
   $this->endsOnDate = Carbon::createFromFormat('Y-m-d', $this->reminder)->addYear()->toDateString();

Livewire will handle the recast to Carbon as per your $casts before passing it back to the view.

1 Like