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

Laravel 8报错Trying to get property 'photos' of non-object求助

解决Trying to get property 'photos' of non-object错误

问题原因

错误出现在视图访问$product->galleries->first()->photos的逻辑中:

  • Product模型的galleries关联是hasMany类型,返回的始终是Collection实例——哪怕没有关联数据,$product->galleries也不是null,所以原代码里的@if($product->galleries)判断完全无效,会直接进入分支执行。
  • 当某个产品没有关联的图库数据时,$product->galleries->first()会返回null,此时继续访问->photos就会触发"获取非对象属性"的错误。

修复方案

方案1:修正视图判断逻辑

修改home.blade.php中的样式部分,先检查图库集合是否有数据,再访问属性:

<div
    class="products-image"
    style="
        @if($product->galleries->isNotEmpty())
            background-image: url('{{ Storage::url($product->galleries->first()->photos) }}');
        @else
            background-color: #eee;
        @endif 
    "
>
</div>

方案2:使用可选链操作符(Laravel 8+支持)

用?->避免空对象调用,同时简化逻辑:

<div
    class="products-image"
    style="
        background-image: url('{{ $product->galleries->first()?->photos ? Storage::url($product->galleries->first()->photos) : '' }}');
        {{ empty($product->galleries->first()?->photos) ? 'background-color: #eee;' : '' }}
    "
>
</div>

额外检查点

  1. 确认product_galleries表中,products_id字段的值与products表的id字段正确关联,且存在对应数据。
  2. 确认模型关联定义正确:当前Product模型的galleries方法中,外键products_id和本地键id的映射无误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 19:01:20