我正在使用Laravel Pusher通知,并且能够在创建行时添加通知,但在更新行时遇到困难。这是
下面的代码CategoryObserver
public function updated(Category $category)
{
$user = Auth::user();
foreach($user->followers as $follower)
{
$follower->notify(new UpdateCategory($user, $category));
}
}
和UpdateCategory
class UpdateCategory extends Notification
{
use Queueable;
/**
* Create a new notification instance.
*
* @return void
*/
public function __construct()
{
//
}
public function via($notifiable)
{
return ['database'];
}
public function toDatabase($notifiable)
{
return [
'following_id' => Auth::user()->id,
'following_name' => Auth::user()->name,
];
}
public function toArray($notifiable)
{
return [
'id' => $this->id,
'read_at' => null,
'data' => [
'following_id' => Auth::user()->id,
'following_name' => Auth::user()->name,
],
];
}
}
答案 0 :(得分:1)
public function updated(Category $category)
{
$user = Auth::user();
foreach($user->followers as $follower)
{
$follower->notify(new UpdateCategory($user, $category));
}
}
//在您的通知中
class UpdateCategory extends Notification
{
use Queueable;
public $user;
public $category;
/**
* Create a new notification instance.
*
* @return void
*/
public function __construct(User $user, Category $category)
{
//
$this->user = $user;
$this->category = $category;
}
public function via($notifiable)
{
return ['database'];
}
public function toDatabase($notifiable)
{
return [
'following_id' => $this->user->id,
'following_name' => $this->user->name,
];
}
public function toArray($notifiable)
{
return [
'id' => $this->id,
'read_at' => null,
'data' => [
'following_id' => $this->user->id,
'following_name' => $this->user->name,
],
];
}
}
您在无法访问的可排队通知中使用Auth()
。从Notification中删除Queueable trait并尝试在Notifications类中注入User对象。
答案 1 :(得分:0)
您的构造函数不会使用您传入的参数。相反,您需要在通知中再次请求它们。
$follower->notify(new UpdateCategory(
$ user,$ category ));
看起来你不需要这个类别,但你应该像这样使用$ user。
///In your controller
$follower->notify(new UpdateCategory($user, $category));
//In UpdateCategory
public function __construct(User $user, Category $category) //Make sure these are "used" at the top
{
$this->user = $user;
$this->category = $category;
}
//Which enables you to use the user *within* the notification later
public function toDatabase($notifiable)
{
return [
'following_id' => $this->user->id,
'following_name' => $this->user->name
];
}
public function toArray($notifiable)
{
return [
'id' => $this->id, //You also aren't really getting this anywhere? Is it supposed to be the category id?
'read_at' => null,
'data' => [
'following_id' => $this->user->id,
'following_name' => $this->user->name
],
];
}
我不确定这是否完全是问题所在,但这绝对是在通知中使用用户的正确方法。