Laravel - convert array into eloquent collection

Viewed 17353

I need to use data from an API.

I create a function:

    public function getItems()
{
    $client = new \GuzzleHttp\Client();
    $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

3 Answers

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

To cast an array into a Illuminate\Database\Eloquent\Collection you can use hydrate() method with the destination Eloquent model, for example:

$eloquentCollection = TheEloquentModel::hydrate($arr);

This is because arrays have index. you can do something like this :

@for ($i = 0; $i < count($vouchers); $i++)
    <p>{{$vouchers[$i]->name}}</p>
@endfor

Update

If each of them included another array, you can try this instead :

@for ($i = 0; $i < count($vouchers); $i++)
    <p>{{$vouchers[$i][0]->name}}</p>
@endfor
Related