Package Data | |
---|---|
Maintainer Username: | jpkleemans |
Maintainer Contact: | jpkleemans@gmail.com (Jan-Paul Kleemans) |
Package Create Date: | 2019-12-16 |
Package Last Update: | 2024-11-06 |
Home Page: | https://attribute.events |
Language: | PHP |
License: | MIT |
Last Refreshed: | 2024-12-17 03:07:50 |
Package Statistics | |
---|---|
Total Downloads: | 325,630 |
Monthly Downloads: | 8,205 |
Daily Downloads: | 361 |
Total Stars: | 311 |
Total Watchers: | 6 |
Total Forks: | 21 |
Total Open Issues: | 3 |
class Order extends Model
{
protected $dispatchesEvents = [
'status:shipped' => OrderShipped::class,
'note:*' => OrderNoteChanged::class,
];
}
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.
composer require jpkleemans/attribute-events
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.
For more info on model events and the
$dispatchesEvents
property, visit the Laravel Docs
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
})
For attributes stored as JSON, you can use the ->
operator:
protected $dispatchesEvents = [
'payment->status:completed' => PaymentCompleted::class,
];
For more complex state changes, you can use attributes defined by an accessor:
class Product extends Model
{
use AttributeEvents;
protected $dispatchesEvents = [
'low_stock:true' => ProductReachedLowStock::class,
];
public function getLowStockAttribute(): bool
{
return $this->stock <= 3;
}
}
For more info on accessors, visit the Laravel Docs
Thanks to Nexxtmove for sponsoring the development of this project.
Code released under the MIT License.