准备:
https://blog.csdn.net/sinat_37390744/article/details/89365517 数据库
https://blog.csdn.net/sinat_37390744/article/details/89387656 邮件
1、创建app\Notifications\NewMessageNotification.php
>>php artisan make:notification NewMessageNotification
写入
<?php
namespace App\Notifications;
use App\Message;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
class NewMessageNotification extends Notification
{
use Queueable;
public $message;
//注入message
public function __construct(Message $message)
{
$this->message = $message;
}
public function via($notifiable)
{
return ['database'];//通过数据库通知
}
public function toDatabase()
{
//存储的内容
return [
'name' => $this->message->fromUser->name,
'dialog' => $this->message->dialog_id,
];
}
public function toArray($notifiable)
{
return [
//
];
}
}
2、控制器使用
//将新的私信写入数据库
$newMessage = Message::create([
'from_user_id' => user()->id,
'to_user_id' => $toUserId,
'body' => \request('body'),
'dialog_id' => $dialogId
]);
//通知用户
$newMessage->toUser->notify(new NewMessageNotification($newMessage));//注入newMessage
3、显示私信列表resources\views\notifications\index.blade.php
@foreach($user->notifications as $notification)
@include('notifications.'.snake_case(class_basename($notification->type)))
@endforeach
4、详情resources\views\notifications\new_message_notification.blade.php
<li class="notifications">
<a href="/inbox/{{$notification->data['dialog']}}">{{$notification->data['name']}}
给您发送了一条私信
</a>
</li>