Aleks Per
Aleks Per

Reputation: 1639

How to convert multidimensional array to collections into Laravel

From an API I have a response a multidimensional array like:

enter image description here

How I can convert this array to eloquent object so I can access in view with $collection->Query->Country or $collection->Carriers->where('id',12345) ...

I try with:

$res1 = collect($res1)->map(function($row) {
    return collect($row);
});

dd($res1);

but no success!

How can I solve this problem?

Upvotes: 1

Views: 579

Answers (1)

Davit Zeynalyan
Davit Zeynalyan

Reputation: 8618

In this case you can use

$collection['Carriers']->where('id',12345)
// or
collect($collection['Carriers'])->where('id',12345)

For make new Eloquent model with attributes you can use

$query =  (new Query())->setRawAttributes($collection['Query']);

then usage

$query->Country;

Or you can do it with this rough way

$model = (new Model())->setRawAttributes($res1);

and usage as you mentioned

$model->Query->Country or $model->Carriers->where('id',12345)

Upvotes: 2

Related Questions