I have this code
$list = Elements::where('list_id', $id)->with('visitors')->get()->sortBy(function($t)
{
return $t->visitors->count();
});
return json_encode($list);
This code returns object, not array. How I can change it?
You should add ->values() if you want an actual JSON array in the end.
As you might add other manipulations like filters and transforms, I'd call ->values() at the very last moment:
return json_encode($list->values());
The reason for using ->values() over other options is that it resets the array keys. If you try returning some associative array (like ['name' => 'Roman'] or even [1 => 'item', 0 => 'other']), it will always get encoded as an object. You need to have a plain array (with sequential integer keys starting at 0) to avoid unexpected things that filtering and sorting will do.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With