Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Broadcasting eloquent events using observers

Currently I am using observers to handle some stuff after creation and updating of my models.

I want to update my app by making it real-time using laravel-echo but I am not able to find documentation regarding the use of laravel-echo in combination with observers (instead of events).

You can use events and their broadcast functionality in combination with their respective listeners to get this functionality but I like the more clean code of observers (less "magic").

Looking at the code of the laravel framework I can see that the observable still uses eloquent events so I do suspect that there is a way to broadcast these.

So my question: is there a way to broadcast eloquent events using laravel-echo without creating individual events or manually adding broadcast statements on every event?

like image 975
milo526 Avatar asked Jul 17 '17 20:07

milo526


1 Answers

Interesting question! We can create a reusable, general-purpose observer that broadcasts events fired from the models that it observes. This removes the need to create individual events for each scenario, and we can continue to use existing observers:

class BroadcastingModelObserver 
{ 
    public function created(Model $model) 
    {
        event(new BroadcastingModelEvent($model, 'created'));
    }

    public function updated(Model $model) { ... }
    public function saved(Model $model) { ... }
    public function deleted(Model $model) { ... }
}

class BroadcastingModelEvent implements ShouldBroadcast 
{
    public $model; 
    public $eventType;

    public function __construct(Model $model, $eventType) 
    {
        $this->model = $model; 
        $this->eventType = $eventType;
    }

    public function broadcastOn() { ... }
}

Then, simply instruct the observer to observe any models that you need to broadcast events to Echo for:

User::observe(BroadcastingModelObserver::class);
Post::observe(BroadcastingModelObserver::class); 
...

As you know, multiple observers can observe the same model. This is a very simple example. We can do a lot of neat things with this pattern. For instance, we could declare which attributes we want to broadcast on each model and configure the event to filter out any that the model doesn't explicitly allow. Each model might also declare the channel that the event publishes to or the type of events that it should broadcast.

Alternatively, we could broadcast the event from your existing observers, but it sounds like you want to avoid adding these statements to each one.

like image 131
Cy Rossignol Avatar answered Oct 10 '22 15:10

Cy Rossignol