jpkleemans / attribute-events

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

Not very clear in docs that it only works for dirty fields #14

Open blite opened 1 year ago

blite commented 1 year ago

I had thought from docs it would work for a created instance if the attributes were set properly.

jpkleemans commented 1 year ago

Hi, thanks for your comment. This is something I have been thinking about as well.

I'm not sure if that should be the default behaviour, because it is hard to check whether a model was created or updated. Especially in a queued event listener.

Perhaps I can add a special syntax to indicate that an event should also be fired on creation of the model (if the attributes were set properly). For example, in vue.js you have an option immediate: true to indicate that an "event" (watched prop) can also be dispatched directly at creation.

Maybe something like this:

protected $dispatchesEvents = [
    'status=shipped' => OrderShipped::class
];

Problem with this is that it introduces a new syntax that is not very explicit.

What do you think?

blite commented 1 year ago

i would use same syntax

        static::created(function ($model) {
            $model->syncOriginalAccessors();
            $model->fireAttributeEvents();
        });

needs to additionally add checks for wasRecentlyCreated to the isDirty checks

ie

isDirty || wasRecentlyCreated

I think wasRecentlyCreated should work as the process that is queueing the event should be the same as the one that created the model, even if you defer object creation to a queue, well its then that queued job that creates the new event.

if I found this wasn't possible. I would just mention it in the docs that it works by monitoring dirty fields and you should manage create events separately.

andreinocenti commented 1 year ago

Hello, Is there any news about this feat? Be able to fire the event on creation or update is something that I would use too