Laravel发送发帖积分通知时报Property [id]不存在错误如何解决
问题根因
- 传参错误:调用
PointAdd通知时你传入了$points变量,但PointAdd构造函数要求接收User实例,givePoint()的返回值并非用户模型,导致后续属性读取逻辑异常 - 关联属性调用错误:用户和帖子为一对多关系,
$this->user->post返回的是帖子集合,而非单条帖子实例,集合本身不存在id属性,直接触发了你遇到的报错
修复步骤
- 修改通知调用逻辑,传入正确的用户实例,同时把刚创建的帖子实例直接传给通知类,避免后续反向查询帖子出现歧义:
// 原错误代码 $points = $user->givePoint(new PostCreated($post)); $user->notify(new PointAdd($points)); // 修改为 $points = $user->givePoint(new PostCreated($post)); $user->notify(new PointAdd($user, $post));
- 调整
PointAdd通知类的属性声明、构造函数和返回数组逻辑:
<?php namespace App\Notifications; use App\Models\Post; use App\Models\User; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Notifications\Messages\MailMessage; use Illuminate\Notifications\Notification; class PointAdd extends Notification { use Queueable; // 新增类属性声明 protected User $user; protected Post $post; /** * 修改构造函数,接收用户和帖子两个参数 */ public function __construct(User $user, Post $post) { $this->user = $user; $this->post = $post; } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { return ['mail', 'database']; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\MailMessage */ public function toMail($notifiable) { return (new MailMessage) ->line('The introduction to the notification.') ->action('Notification Action', url('/')) ->line('Thank you for using our application!'); } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ public function toArray($notifiable) { return [ 'user_id' => $this->user->id, 'user_name' => $this->user->name, 'user_avatar' => $this->user->avatar, 'user_points' => $this->user->reputation, // 直接用传入的post实例取id,不再通过用户关联反向查询 'post_id' => $this->post->id, ]; } }
内容的提问来源于stack exchange,提问作者INSIDECAMPUS TV
相关产品推荐
相关产品推荐

