laravel / framework

The Laravel Framework.
https://laravel.com
MIT License
32.64k stars 11.04k forks source link

[11.x] Enable listening to multiple Eloquent events #53539

Closed istiak-tridip closed 3 days ago

istiak-tridip commented 5 days ago

Description

This PR introduces a new Model::listen method, allowing developers to listen to multiple Eloquent events at once.

This enhancement improves the developer experience and aligns with the existing Event::listen behavior. Additionally, it introduces support for wildcard event listening for Eloquent models.

Currently, performing the same action for multiple events looks like this:

Categories::created(function () {
    Cache::forget('categories');
});

Categories::deleted(function () {
    Cache::forget('categories');
});

With This PR:

Categories::listen(['created', 'deleted'], function () {
    Cache::forget('categories');
});

// Listen to all Eloquent events for the model
Categories::listen(function () {
    // Do something
});

Looking forward to hearing your thoughts! Thank you for all the amazing work you guys do! 🙏


Previous attempt: #49949 — I’ve optimized the implementation, enhanced the "wildcard listener" dx, and added more comprehensive tests in this iteration.

taylorotwell commented 3 days ago

Hey @istiak-tridip, would you mind sending this to the master branch? A listen method is could be somewhat common in user land Eloquent models and if users have already defined a listen method on their models this could break it. We would need to include this in the upgrade guide.

Thanks!

istiak-tridip commented 2 days ago

@taylorotwell As suggested, I’ve created a new PR #53562 targeting the master branch. Looking forward to your feedback. Thanks!