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

Laravel belongsTo关联失效 报Attempt to read property "seen" on null错误

问题原因

报错Attempt to read property "seen" on null是因为你尝试访问的$notify->Notification为null,核心错误点有3个:

  1. 模型关联定义逻辑错误
  2. Blade中关联调用名不匹配
  3. 未处理关联记录不存在的边界情况

修复步骤

1. 修正模型关联

你的notificationseens表存储了外键notificationID,属于从属表,notifications是主表,关联关系写反了。同时要加当前登录用户的过滤,否则会拿到其他用户的已读状态:

<?php
// App\Models\Backend\Notification.php
namespace App\Models\Backend;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Notification extends Model
{
    use HasFactory;
    protected $table = 'notifications';

    // 修正为hasOne关联,加当前用户过滤,拿取当前登录用户的已读记录
    public function notificationseen()
    {
        return $this->hasOne(notificationseen::class, 'notificationID', 'id')
            ->where('userid', auth()->id());
    }
}

notificationseen模型的关联无需修改,仅建议把方法名改为小写符合Laravel命名规范:

<?php
// App\Models\Backend\notificationseen.php
namespace App\Models\Backend;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class notificationseen extends Model
{
    use HasFactory;
    protected $table = 'notificationseens';

    // 方法名改为小写符合规范
    public function notification()
    {
        return $this->belongsTo(Notification::class, 'notificationID');
    }
}

2. 控制器查询预加载关联

查询通知时预加载关联,避免N+1性能问题:

// 你的控制器方法中
$notification = Notification::with('notificationseen')->get();
return view('你的视图路径', compact('notification'));

3. 修正Blade判断逻辑

替换原本的判断条件,处理关联为空的情况:

  • 如果你的业务逻辑是通知下发时就给接收用户插入seen=0的记录,直接用Laravel的optional辅助函数避免null报错:
@if(optional($notify->notificationseen)->seen == 0)
  • 如果你的业务逻辑是用户首次点击通知才插入已读记录,没有记录就代表未读,判断逻辑改为:
@if(empty($notify->notificationseen) || $notify->notificationseen->seen == 0)

如果使用PHP7.4及以上版本,也可以用null安全运算符写法:

@if($notify->notificationseen?->seen == 0)

内容的提问来源于stack exchange,提问作者Md Arif

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 11:36:08