0
点赞
收藏
分享

微信扫一扫

Laravel技巧集锦(39):使用notification实现站内通知(私信通知)


准备:


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>

 

 

举报

相关推荐

0 条评论