I am returning some data from DB using Eloquent and putting in in object of arrays. My response object to browser is displayed in this format:
// response()->json($response, 200);
[{
"id": 1,
"name": "car",
"make": ["bmw", "ford"]
"order": 1
},
{
"id": 2,
"name": "bike",
"make": ["aprilia"]
"order": 2
},
{
"id": 3,
"name": "boat",
"make": []
"order": 3
},
(...)
]
Before returning it though, I wanted to filter it on server side. So I only return objects which do hold value in the "make" array.
So I am running this loop:
foreach ($response as $key => $transport) {
if (count($response[$key]['make']) == 0) {
unset($response[$key]);
};
}
What php does is it converts the array to object and also adds keys to each inner object. So now my $response looks like:
// response()->json($response, 200);
{ // notice here it has changed from array to object
"0": { // notice here it has added key "0"
"id": 1,
"name": "car",
"make": ["bmw", "ford"]
"order": 1
},
"1" : { // notice here it has added key "1"
"id": 2,
"name": "bike",
"make": ["aprilia"]
"order": 2
},
(...)
}
First of all - why? And second question - how to prevent/go back to array of objects response?
collect()method. I tried to usetoArray()methods provided by Laravel, but no joy.array_values()because(array)will retain the nun sequential indexes.