Ralph Christian Eclipse Ralph Christian Eclipse - 27 days ago 36
PHP Question

Laravel 5.3 Broadcast using Laravel Echo via Pusher using Models Creating, Saving Etc events

Is there a way to implement this

as documented in this link Event of Models

How can i extend those events to fire broadcast pusher data, rather than making separate events for the model

Answer

You could do it a number of ways. If you want to catch ALL model events you can register a wildcard listener. In your App\Providers\EventServiceProvider in the boot method register the wildcard listener:

public function boot()
{
    parent::boot();

    Event::listen('eloquent.*', function (array $data) {
        broadcast(new YourModelEventListener($data));
    });
}

Or if you want to keep the logic separate for each model you could create a class observer catch all the events and send to your broadcast handler.

Register the observer

class MyModel extends Model
{
    protected static function boot()
    {
        parent::boot();

        static::observe(new MyModelObserver);
    }
}

Then in the observer:

class MyModelObserver
{
    public function broadcast($method, $model)
    {
        broadcast(new YourModelEventListener($method, $model));
    }

    public function creating($model)
    {
        $this->broadcast('creating', $model);
    }

    public function updating($model)
    {
        $this->broadcast('updating', $model);
    }
}