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

准备:

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>

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值