【问题标题】:how to make real-time laravel 5.3 Notifications如何制作实时 laravel 5.3 通知
【发布时间】:2017-01-16 08:30:22
【问题描述】:

我正在使用 Laravel 5.3 通知。

我成功创建了数据库通知以及如何向目标用户显示所有或未读的通知。

例如,这是我的通知类,通知用户她在课程中的注册状态:

class NewChangeRegisterStatusNotif extends Notification
{
    use Queueable;


    public function __construct ($status_id, $course_id)
    {
        $this->status = CourseUserStatus::findOrFail($status_id);
        $this->course = Course::findOrFail($course_id)->first(['title']);
    }


    public function via ($notifiable)
    {
        return ['database'];
    }


    public function toMail ($notifiable)
    {
        return (new MailMessage)
            ->line('The introduction to the notification.')
            ->action('Notification Action', 'https://laravel.com')
            ->line('Thank you for using our application!');
    }


    public function toArray ($notifiable)
    {
        return [
            'message' =>
                ' Your Status in ' .
                '<strong class="text-default">' . $this->course->title . '</strong>'
                . ' Course has changed to  ' .
                '<strong class="text-' . $this->status->label . '">' . $this->status->title . '</strong>';

            ,
            'action'  => '#'
        ];
    }
}

并显示我在刀片模板中编写的所有通知:

<ul class="menu">
    @foreach($AuthUser->unreadNotifications as $notif)
        <li>
            <a href="{{$notif->data['action']}}" data-notif-id="{{$notif->id}}">
                {!! $notif->data['message'] !!}
            </a>
        </li>
    @endforeach
</ul>

一切正常,但现在我想实现它的实时性。

我知道我可以使用Pusher 和Pusher bridge。我安装 Pusher 桥接器并遵循Building Real-Time Laravel Apps with Pusher 指导。

但我不知道如何在我的通知中使用它?如何在via() 方法中定义它?我该怎么做?

【问题讨论】:

    标签: php laravel laravel-5.3


    【解决方案1】:

    现在您创建了管理通知的后端。

    您在视图中所做的只是显示来自服务器端渲染的通知(即在加载新页面时)。

    如果您真的想要实时通知(我假设您这样做是因为您提到了推送器),您需要将通知从服务器推送到应用程序的客户端代码。

    按照您提到的教程,推送服务器端是使用以下代码完成的:

    $pusher->trigger( 'test-channel',
                      'test-event', 
                      array('text' => 'Preparing the Pusher Laracon.eu workshop!'));
    

    在这里,您的 laravel 应用程序将向推送者推送消息。您所要做的就是设置您的客户端(您的 javascript)以接收并显示它。

    这部分可以使用这种javascript代码来完成:

    var pusher = new Pusher('{{env("PUSHER_KEY")}}');
    var channel = pusher.subscribe('channel-name');
    channel.bind('event-name', function(data) {
        // do something with the event data
    });
    

    现在由您来决定是否显示该通知。它可以像 console.log 一样简单,也可以像创建新的 html 元素并将它们添加到菜单中那样复杂。

    很抱歉没有提出实际的代码,但我希望我能让你更清楚,这样你就可以继续下去了。

    【讨论】:

    • 谢谢@Atrakeur,但我的主要问题是我必须在哪里打电话给$pusher-&gt;trigger( 'test-channel'...?我正在寻找一种NewChangeRegisterStatusNotif 通知可以自动完成所有后端工作的方法。
    猜你喜欢
    • 2017-04-27
    • 2017-04-02
    • 1970-01-01
    • 1970-01-01
    • 2017-10-11
    • 2017-04-23
    • 1970-01-01
    • 2017-08-22
    • 2017-09-01
    相关资源
    最近更新 更多