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

Laravel控制器传解码数组到视图后无法获取内容,报非对象属性错误

Fixing "Trying to get property of non-object" in Laravel Blade Loop

Hey there, let's work through this issue step by step to get your loop working correctly:

1. The Root Cause: Arrays vs. Objects

In your AddressController.php, you're using json_decode($pro, true) — that second true parameter tells PHP to return an associative array instead of an object. But in your Blade template, you're trying to access values with object syntax (->name), which doesn't work for arrays. That's exactly why you're seeing the "Trying to get property of non-object" error.

2. Bonus Typo to Fix

You also have a variable name mismatch in your loop: you defined $cartItem in the @foreach line, but then tried to reference $cartItems (plural) when accessing price and quantity. That would throw an undefined variable error once you fix the first issue, so we'll fix that too.

Corrected Blade Code

Here's the fixed version of your loop using array syntax (since your controller is returning an array):

@foreach($pro_array as $cartItem)
    <p>Products: {{ $cartItem['name'] }}</p>
    <p>Unit Price: {{ $cartItem['price'] }} X {{ $cartItem['quantity'] }}</p>
@endforeach

Alternative: Use Object Syntax Instead

If you'd prefer to stick with object syntax in your Blade file, you can modify the json_decode line in your controller to remove the true parameter. This will return objects instead of arrays:

$pro_array = json_decode($pro); // No second parameter = returns objects

Then your Blade code (with the fixed variable name) would work as you originally wrote it:

@foreach($pro_array as $cartItem)
    <p>Products: {{ $cartItem->name }}</p>
    <p>Unit Price: {{ $cartItem->price }} X {{ $cartItem->quantity }}</p>
@endforeach

Either approach works — just pick the one that fits your coding style!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:12:47