一、创建通知
执行命令
php artisan make:notification NewMessageNotification
修改生成的文件:app/Notifications/NewMessageNotification.php
namespace App\Notifications;
use App\Message;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
class NewMessageNotification extends Notification
{
use Queueable;
public $message;
public function __construct(Message $message)
{
$this->message = $message;
}
public function via($notifiable)
{
return ['database'];
}
public function toDatabase($notifiable)
{
return [
'name' => $this->message->fromUser->name,
'dialog' => $this->message->dialog_id,
];
}
public function toArray($notifiable)
{
return [
];
}
}
二、发送通知
修改app/Repositories/MessageRepository.php
use App\Notifications\NewMessageNotification;
public function store($dialogId)
{
$message = Message::where('dialog_id', $dialogId)->first();
$toUserId = $message->from_user_id === user()->id ? $message->to_user_id : $message->from_user_id;
$newMessage = Message::create([
'from_user_id' => user()->id,
'to_user_id' => $toUserId,
'content' => request('content'),
'dialog_id' => $dialogId
]);
return $newMessage->toUser->notify(new NewMessageNotification($newMessage));
}
三、查看通知
新建 resources/views/notifications/new_message_notification.blade.php