jpkleemans/attribute-events

Multiple column checks for a single event

techdaddies-kevin opened this issue · 2 comments

We want to fire an event when any one of several DB columns are updated on our User model. This event reaches out to an external API and updates other columns on the User model. The problem we're running into is that the event is being fired multiple times if multiple attribute events are a hit. Here is what our definition looks like:

protected $dispatchesEvents = [
        'birthdate:*'         => UserBirthInfoChanged::class,
        'birthtime:*'         => UserBirthInfoChanged::class,
        'birthplace:*'    => UserBirthInfoChanged::class,
    ];

Obviously we want to fire UserBirthInfoChanged when ANY of those columns are updated. But only once for any given update. I'm not sure if this is currently possible, but looking at the fireAttributeEvents method, it doesn't seem like it is.

Hi, thanks for your question. That isn't possible at the moment indeed. But maybe there's a workaround.
You could for example create specific events per property and attach the same listener to those 3 events.
Does that help you?

    protected $dispatchesEvents = [
        'user_birth_info_changed:true' => UserBirthInfoChanged::class,
    ];

    public function getUserBirthInfoChangedAttribute(): bool
    {
        return !empty(
        array_intersect(
            [
                'birthdate',
                'birthtime',
                'birthplace',
            ],
            array_keys($this->getChanges())
        )
        );
    }