jpkleemans / attribute-events

🔥 Fire events on attribute changes of your Eloquent model
https://attribute.events
MIT License
309 stars 20 forks source link

Doesn't work with attributes cast #8

Closed denisgoryaynov closed 2 years ago

denisgoryaynov commented 2 years ago

When casting attributes with protected $casts = [] the changes are not picked up and the relative events are not fired, for example I am using spatie/laravel-model-states to keep the status of a request with the following $casts:

protected $casts = [
     'status' => RequestStatus::class,
];

And the following $dispatchesEvents:

protected $dispatchesEvents = [
      'created' => RequestCreated::class,
      'status:confirmed' => RequestConfirmed::class,
      'status:repaired' => RequestCompletedIntervention::class,
];

In this case the events are not fired because the Trait AttributeEvents compares the values like this on line 64: $value === $expected, but because of the cast my value is not a string but an instance of a RequestStatus. Comparing the values with $value == $expected works because the RequestStatus can be cast to a string. I tried adding $this->castAttribute($attribute, $expected) but I keep getting the current value of the attribute and not the $expected value I want to cast, I don't know if it's how laravel is supposed to work. For now I ended up doing $value = $this->getAttributes()[$attribute]; on line 32 and I get the expected resault

jpkleemans commented 2 years ago

Hi Denis, thanks for your issue report.

Does it work when using (string) $value === $expected on line 64 of AttributeEvents? If that doesn't work, can you reproduce the issue on a PHPSandbox notebook? So I can look into it.

denisgoryaynov commented 2 years ago

Hi, casting with (string) $value === $expected produces the expected result

jpkleemans commented 2 years ago

Thanks, I'll work on a way to support all castables.

jpkleemans commented 2 years ago

I've added support for Castables in v1.2.0. This should fix your problem :)