【问题标题】:Trying to get property 'price' of non-object试图获得非对象的财产“价格”
【发布时间】:2021-09-15 21:55:32
【问题描述】:

我正在使用 Laravel 5.8 开发我的项目,在这个项目中,我想检查用户的购物车价格是否超过自定义数字(也应该从数据库中获取),然后打印 @ 987654323@.

所以为了做到这一点,我添加了这个:

@foreach(\App\Shop\ProductDelivery::find(1) as $delivery)
    @if($cartPrice >= $delivery->price)
        <i>
        You delivery is free
        </i>
    @endif
@endforeach

但它显示了这个错误:

试图获取非对象的属性“价格”

参考这一行:

<?php if($cartPrice >= $delivery->price): ?>

然而价格已经存在于数据库中:

那么这里出了什么问题?我该如何解决这个问题?

【问题讨论】:

    标签: php laravel eloquent laravel-5.8


    【解决方案1】:

    \App\Shop\ProductDelivery::find(1) 只返回一条记录,因此在这种情况下使用 foreach 会导致您的问题。要解决它,您可以将代码更改为:

    @php
      $delivery = \App\Shop\ProductDelivery::find(1)
    @endphp
    @if($delivery && $cartPrice >= $delivery->price)
        <i>
        You delivery is free
        </i>
    @endif
    

    或者,如果您仍然想使用 foreach,尽管它不是必需的:

    @foreach(\App\Shop\ProductDelivery::where('id', 1)->get() as $delivery)
      @if($cartPrice >= $delivery->price)
        <i>
        You delivery is free
        </i>
      @endif
    @endforeach
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-09
      • 2020-08-20
      • 1970-01-01
      • 1970-01-01
      • 2020-11-25
      • 1970-01-01
      相关资源
      最近更新 更多