使用pusher在数据库添加时触发Laravel 5通知

I've decided to implement real-time notifications into my app.

The notifications need to happen on certain events most of which would need to be triggered on updates to tables in the database.

To have it happen in real-time I'm currently using a free account with pusher and I'm willing to upgrade if and when the app scales.

However I'm pretty lost as to how to have Laravel 5 events trigger on updates to a table.

Currently I have triggers in the database that add records to a notifications table when ever updates are made to certain tables. Ideally I'd have a Laravel 5 event fire whenever a record is added here and this would in turn use pusher to instantaneously send a notification.

Can anyone offer me direction or a good tutorial?


I essentially want clarity on where best to test that updates were successfully made to the database. Laravel events can be cast every time the ->save() method is called but in the case of notifications, that table updates based on database triggers so no code is relevant.

Assuming when you say database triggers, you mean Laravel saving events and not actual database triggers, you could do something like this:

class Notification extends Model {

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

        static::created(function(Notification $notification) {
            event(new PusherEvent());
        });
    }
}

class OtherModel extends Model {

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

        static::updated(function(OtherModel $model) {
            Notification::create();
        });
    }
}

The OtherModel class is a representation of all other models in your app which have this trigger to create a notification. If your trigger is an actual database trigger however, this will not work and I recommend you move over to the eloquent way of creating a trigger.

I recently ran a Building Real-Time Laravel Apps with Pusher workshop at Laracon EU. The workshop exercises (linked to above and with a section on Notifications) will walk you through how you can either integrate Pusher via a bridge library or the built in Pusher Event Broadcaster (in Laravel 5.1 and above).

It doesn't cover database interactions, but a very quick summary of the normal strategy for triggering a notification is:

  1. Interact with the database
  2. Ensure the interaction was successful
  3. Trigger an event via Pusher
  4. Receive the event on the client
  5. Show the notification