php - 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的结果:
解决方案
基本上,您的错误是由其他通知数据库上没有“线程”引起的。你怎么能防止呢?只需添加一个类型来区分通知视图,您需要用类型名称告诉其他所有通知,可能是其他hasPost、createSome或其他。
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-Websockets
Laravel-Echo
推荐阅读
- terraform - 是否可以在没有状态文件的情况下使用 terraform 销毁 ec2 实例
- sql-server - 如何将集合从 TFS 2017 迁移到 Azure DevOps Server 2019(不同的数据库服务器)
- c# - AdaptiveCard Bot Framework V4 中的日文字符
- visual-studio-code - 使用 Visual Studio Code 的 REST 客户端扩展的 POST 请求
- javascript - 多次显示警报
- javascript - 如何解决这个 CSS 不是函数错误
- php - 向除发件人以外的所有用户发布消息
- r - 直接从 VisEvents 调用 R 函数
- javascript - 在浏览器中安装 AdBlock 扩展时,如何使用 Blob 在新页面中显示 pdf\jpg 文件
- c# - 如何通过列表
从 C# 到 C++ CLi?