drap5081683 2015-09-15 16:26
浏览 34
已采纳

使用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.

  • 写回答

2条回答 默认 最新

  • douju1852 2015-09-16 10:34
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?