首页 > 解决方案 > 尝试在刀片中获取非对象属性时出错

问题描述

所以我试图传递数据来查看:

$orders = $this
        ->query()
        ->where('user_id', '=', $id)
        ->with(['payment', 'payment.paymentStatus'])
        ->get();

return view('profile.profile-orders', compact('orders'));

我得到这个有效载荷:

{
  "id": 4,
  "order_id": 4,
  "status": 1,
  "price": 897,
  "payment_date": "2021-10-11 18:11:50",
  "payment_status": {
    "id": 1,
    "title": "Not paid",
    "status_color": "#d1dade",
  },
  "order": {
    "id": 4,
    "customer_id": 4,
    "created_at": "2021-10-11T18:11:33.000000Z",
    "updated_at": "2021-10-11T18:11:33.000000Z",
    "items": [
      {
        "id": 5,
        "amount": 1,
        "price": 697,
        "product": {
          "id": 1,
          "price": "697.00",
          "order": 1,
          "images": [
            {
              "img": "image1"
            },
            {
              "img": "image2"
            }
          ],
        }
      }
    ]
  }
}

在我看来,我试图得到payment_status->title

@foreach($orders as $order)
<tr>
   <td>{{ $order->payment->payment_status->title }}</td>
</tr>
@endforeach

但我收到此错误Trying to get property 'title' of non-object如何解决此错误?

标签: phplaravel

解决方案


我认为您需要的只是数组访问([])而不是对象访问(->)。所以你的代码应该是:

@foreach($orders as $order)
<tr>
   <td>{{ $order->payment->payment_status['title'] }}</td>
</tr>
@endforeach

推荐阅读