- 創(chuàng)建通知
>php artisan make:notification SendMail
在App\Notifications
下面找到剛才創(chuàng)建的通知類打開并編輯.
//SendMail.php
public function via($notifiable)
{
return ['database'];
}
via
方法指定通知使用何種渠道發(fā)送,laravel內(nèi)置的有mail
,database
,'broadcast',nexmo
,slack
這里我們指定database
即通過數(shù)據(jù)庫發(fā)送消息.
通過何種渠道發(fā)送消息則該類下面必須有一個ToXXX
的方法,例如database
渠道則必須有一個ToDatabase
方法,mail
則必須有一個ToMail
對應(yīng).
- 新建方法
//SendMail.php
public function toDatabase($notifiable)
{
return [
'uid'=>99,
'money'=>'$100',
'content'=>$this->content
];
}
- 創(chuàng)建數(shù)據(jù)表
>php artisan notifications:table
>php artisan migrate
此時在數(shù)據(jù)庫里面已經(jīng)可以看到notifications
表,它將用來存儲消息通知. - 發(fā)送消息
//XxxController.php
在控制器中use Notifiable;
class TestController extends Controller
{
use Notifiable;
//發(fā)送消息通知測試
public function test()
{
//$user必須是一個用戶實例,表示此消息發(fā)送給某個用戶
//根據(jù)測試一次只能發(fā)給一個用戶,如果可以發(fā)送多個用戶歡迎留言.
$user = User::find(1);
$user->notify(new SendMail('消息功能測試'));
}
通過瀏覽器訪問一下方法,此時已經(jīng)可以在數(shù)據(jù)表notifications
中的data
字段看到剛才發(fā)送的內(nèi)容了.
- 查看消息
//消息通知讀取,也可以讀取所有的和未讀的,具體歡迎看文檔.
public function show()
{
$user = User::find(1);
foreach ($user->Notifications as $notification) {
dump($notification->data);
}
}
End