Laravel Notifications toDatabase

参考:
消息通知

Prepare notification database

1
2
3
4
5
php artisan notifications:table
php artisan migrate

#add users table notification_count column
php artisan make:migration add_notification_count_to_users_table --table=users

Generate notification class

1
php artisan make:notification

app/Notifications/TopicReplied

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
<?php

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use App\Models\Message;
use Auth;

class TopicReplied extends Notification
{
use Queueable;

/**
* Create a new notification instance.
*
* @return void
*/
public $message;
public $topic;

public function __construct(Message $message)
{
$this->message = $message;
}

/**
* Get the notification's delivery channels.
*
* @param mixed $notifiable
* @return array
*/
public function via($notifiable)
{
return ['database'];
}



/**
* Get the array representation of the notification.
*
* @param mixed $notifiable
* @return array
*/
public function toArray($notifiable)
{

return [
'from'=>Auth::user()->name,
'message'=>$this->message->content,
];
}
}

Get all notifications,use Notifiable trait

1
2
3
4
5
$notifications = $user->notifications()->paginate(20);
# get the serialize data by toArray() method
$notification->data toArray() data

$user->notify(new TopicReplied($message))

MarkAsRead

1
$user->unreadNotifications->markAsRead();