No error or output shows up when decoding in laravel view.
The function in my controller
public function getOrderHistory(){
$orders = Processing::where('client_id', auth()->user()->id)->get('order_details');
return view('pages.purchase', compact('orders', json_decode($orders)));
}
My Laravel View
@foreach ($orders as $order)
<h5 >{{ $order->name }}</h5>
<p >Accepted</p>
<div >
<h6 >Price: $100</h6>
</div>
@endforeach
Mysql order_details column
{"order_id":2,"quantity":1,"name":"Atque beatae quia omnis."}
CodePudding user response:
It's because your $orders
is actual array containing JSON values:
$orders = [
'{"order_id":2,"quantity":1,"name":"Atque beatae quia omnis."}',
/* ... */
];
so your json_decode
does not work on array (use json_last_error_msg()
to get errors.
In order to decode all your orders, you can do
$orders = array_map('json_decode', $orders); // pass each element of $orders into `json_decode`
Since you are storing all info into single column I assume that your database structure is bad and will cause issues in future. E.g. finding all orders with quantity > 3
. Maybe better have separate columns for that or whole table mapped by Foreign Keys?
CodePudding user response:
your $order is collection of Processing model! json_decode function not work in collection.
your $orders variable in foreach blade is first passed value from controller (collection of order model) not decoded value
delete json_decode($orders) :
public function getOrderHistory(){
$orders = Processing::where('client_id', auth()->user()->id)->get('order_details');
return view('pages.purchase', compact('orders'));
}
change view to bellow:
@foreach ($orders as $order)
@php
$order_data=json_decode($order->order_details , true);
@endphp
<h5 >{{ $order_data['name'] }}</h5>
<p >Accepted</p>
<div >
<h6 >Price: $100</h6>
</div>
@endforeach