Does this help? https://tighten.co/blog/laravel-tip-bootable-model-traits
How to add observable events and use in an observer
TL;DR - How do I register custom observable events from a trait and observe those from another via an observer instance?
I created a global scope, called CancellingScope. Analogous to how soft deleting works, but it is intended for regular users instead of users with elevated access.
I need to be able to listen to the cancelled event via a model observer to remove it from the Elastic Search index because I do not want people to be able to search for cancelled entities.
I examined the HasEvents trait and it exposes a class method called addObservableEvents. The problem is that this is a class method, not static and typically in a trait you register model observers statically, like so:
public static function bootTrait()
{
static::observe(new ModelObserver);
}
-
I tried using a class method with the initialize prefix, but those methods are executed after the booting ones, so when it is way too late.
-
I looked at how soft deleting does this, but apparently it's just a hard-coded array and does not use the addObservableEvents method. I tried overloading the $observables property, with no avail (throws exception).
Basically, what I want to achieve:
- Add custom (observable) events via Cancels.php (trait)
- Register observer that listens to those events via Searchable.php (trait)
Could anyone help me out with this? Thanks in advance.
Please or to participate in this conversation.