I need to use data from an API.
I create a function:
JavaScript
x
public function getItems()
{
$client = new GuzzleHttpClient();
$res = $client->get('https://app.example.com/api/getItems');
$vouchers = json_decode($res->getBody(), true);
dd($vouchers);
return view('api', compact('vouchers'));
}
and dd($vouchers)
return me:
Now when I try to use $vouchers array with blade engine like:
JavaScript
<body>
@foreach ($vouchers as $v)
<p>{{$v->name}}</p>
@endforeach
</body>
I got error:
JavaScript
"Trying to get property 'name' of non-object (View: .... etc...
How I can convert array into eloquent collection. I use the latest Laravel 5.7 version
Advertisement
Answer
Actually your $vouchers
is an array of arrays,
So you may want to convert your sub-arrays to objects:
You can do it simply using:
JavaScript
foreach ($vouchers['vouchers'] as $key => $value) {
$vouchers['vouchers'][$key] = (object) $value;
}
.. or using collections:
JavaScript
$vouchers = collect($vouchers['vouchers'])->map(function ($voucher) {
return (object) $voucher;
});