首页 > 解决方案 > Laravel 8:如何在刀片上正确返回通知

问题描述

我正在使用 Laravel 8 开发我的项目,这是一个在线论坛,对于这个项目,我想添加一些通知功能,如果有人回答了他在论坛上提出的问题,可以提醒用户。

所以基本上,当有人回答问题时,这个方法会运行:

public function postAnswer(Question $id)
{
    $validate_data = Validator::make(request()->all(),[
        'answer' => 'required',
    ])->validated();

    $answer = Answer::create([
        'answer' => $validate_data['answer'],
        'user_id' => auth()->user()->id,
        'question_id' => $id,
    ]);

    auth()->user()->notify(new RepliedToThread($id)); // making new notification

    return back();
}

然后,我创建了这个通知,名为RepliedToThread.php

class RepliedToThread extends Notification
{
    use Queueable;

    protected $thread;

    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct($id)
    {
        $this->thread = $id;
    }

    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        return ['database'];
    }

    /**
     * Get the array representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function toDatabase($notifiable)
    {
        return [
            'thread' => $this->thread,
            'user' => $notifiable
        ];
    }

    /**
     * Get the array representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function toArray($notifiable)
    {
        return [
            //
        ];
    }
}

如您所见,我定义了一个名为的受保护变量$thread,并将其分配给$id来自以下的变量:auth()->user()->notify(new RepliedToThread($id));

之后,我尝试通过以下方式返回它们:

public function toDatabase($notifiable)
    {
        return [
            'thread' => $this->thread,
            'user' => $notifiable
        ];
    }

最后,我将它添加到刀片中:

<a href="">
   {{$notification->data['thread']['title']}}</strong>
</a>

但现在我得到这个错误:

ErrorException未定义索引:线程

所以我真的不知道这里出了什么问题!所以如果你知道如何解决这个问题,请告诉我,我真的很感激你们的任何想法或建议......

这也是我的桌子notifications,如果你想看看:

在此处输入图像描述

这也是{{ dd($notification) }}on Blade的结果:

在此处输入图像描述

标签: phplaravellaravel-8

解决方案


基本上,您的错误是由其他通知数据库上没有“线程”引起的。你怎么能防止呢?只需添加一个类型来区分通知视图,您需要用类型名称告诉其他所有通知,可能是其他hasPostcreateSome或其他。

public function toDatabase($notifiable)
    {
        return [
            'thread' => $this->thread,
            'user' => $notifiable,
            'type' => 'RepliedThread'
        ];
    }

然后在您的通知刀片中,您只需使用它if statement来检查那是什么类型

@forelse(auth()->user()->unreadNotifications as $notification)
@if($notification->data['type'] == "RepliedThread")
  <a href="">
   {{$notification->data['thread']['title']}}</strong>
</a>
@endif
@empty
no notification
@endforelse

对于您需要使用WebSockets Server的实时通知,有一个第 3 方,它称为Pusher,或者如果您想使用自己的 WebSocket 服务器,Laravel 有. 如果你深入挖掘,你会发现Laravel-WebsocketsLaravel-Echo


推荐阅读