You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel发送发帖积分通知时报Property [id]不存在错误如何解决

问题根因
  • 传参错误:调用PointAdd通知时你传入了$points变量,但PointAdd构造函数要求接收User实例,givePoint()的返回值并非用户模型,导致后续属性读取逻辑异常
  • 关联属性调用错误:用户和帖子为一对多关系,$this->user->post返回的是帖子集合,而非单条帖子实例,集合本身不存在id属性,直接触发了你遇到的报错
修复步骤
  1. 修改通知调用逻辑,传入正确的用户实例,同时把刚创建的帖子实例直接传给通知类,避免后续反向查询帖子出现歧义:
// 原错误代码
$points = $user->givePoint(new PostCreated($post));
$user->notify(new PointAdd($points));

// 修改为
$points = $user->givePoint(new PostCreated($post));
$user->notify(new PointAdd($user, $post));
  1. 调整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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 00:15:04