[英]how to make real-time laravel 5.3 Notifications
我正在使用Laravel 5.3 Notifications。
我成功創建了數據庫通知以及如何向目標用戶顯示所有或未讀的數據庫通知。
例如,這是我的通知類,通知用戶在課程中注冊狀態:
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橋 。 我安裝了Pusher橋,並使用Pusher指導跟隨Building Real-Time Laravel應用程序 。
但我不知道如何在我的通知中使用它? 如何在via()
方法中定義它?我該怎么做?
現在您創建了管理通知的后端。
您在視圖中執行的操作是顯示來自服務器端呈現的通知(即,在添加新頁面時)。
如果你真的想要實時通知(我假設你這樣做是因為你提到了推送器),你需要將服務器的通知推送到應用程序的客戶端代碼。
根據您提到的教程,推送服務器端使用以下代碼完成:
$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元素並將它們添加到菜單中。
很抱歉沒有提出實際的代碼,但我希望我為你做的更清楚,這樣你就可以繼續。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.