Laravel控制器传解码数组到视图后无法获取内容,报非对象属性错误
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

