Skip to content
Advertisement

Laravel – convert array into eloquent collection

I need to use data from an API.

I create a function:

    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:

enter image description here

Now when I try to use $vouchers array with blade engine like:

<body>
              @foreach ($vouchers as $v)
                <p>{{$v->name}}</p>
              @endforeach
          </body>

I got error:

"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:

foreach ($vouchers['vouchers'] as $key => $value) {
    $vouchers['vouchers'][$key] = (object) $value;
}

.. or using collections:

$vouchers = collect($vouchers['vouchers'])->map(function ($voucher) {
    return (object) $voucher;
});

Laravel collections documentation

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement