Blog Detail

07

Jan
Fire Events on Attribute Changes of Laravel Eloquent Model cover image

arrow_back Fire Events on Attribute Changes of Laravel Eloquent Model

Eloquent models fire several handy events throughout their lifecycle, like created and deleted. However, there are usually many more business meaningful events that happen during a model’s life. With this library, you can capture those, by mapping attribute changes to your own event classes.

Installation

composer require jpkleemans/attribute-events

How to use it

Use the Kleemans\AttributeEvents trait in your model and add the attributes to the $dispatchesEvents property:

class Order extends Model
{
    use AttributeEvents;

    protected $dispatchesEvents = [
        'created'         => OrderPlaced::class,
        'status:canceled' => OrderCanceled::class,
        'note:*'          => OrderNoteChanged::class,
    ];
}

The attribute events will be dispatched after the updated model is saved. Each event receives the instance of the model through its constructor.

Listening

Now you can subscribe to the events via the EventServiceProvider $listen array, or manually with Closure based listeners:

Event::listen(function (OrderCanceled $event) {
    // Restock inventory
});
Or push realtime updates to your users, using Laravel's broadcasting feature:

Echo.channel('orders')
    .listen('OrderShipped', (event) => {
        // Display a notification
    })

JSON attributes

For attributes stored as JSON, you can use the -> operator:

protected $dispatchesEvents = [
    'payment->status:completed' => PaymentCompleted::class,
];

Accessors

For more complex state changes, you can use attributes defined by an accessor:

class Product extends Model
{
    protected $dispatchesEvents = [
        'low_stock:true' => ProductReachedLowStock::class,
    ];

    public function getLowStockAttribute(): bool
    {
        return $this->stock <= 3;
    }
}

If you want to learn more about this package you can visit its documentation on Github.

Published at : 07-01-2022

Author : Rizwan Aslam
AUTHOR
Rizwan Aslam

I am a highly results-driven professional with 12+ years of collective experience in the grounds of web application development especially in laravel, native android application development in java, and desktop application development in the dot net framework. Now managing a team of expert developers at Codebrisk.

Launch your project

Launch project