Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sortBy returns object instead of array

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?

like image 919
helloRoman5556 Avatar asked Feb 16 '26 12:02

helloRoman5556


1 Answers

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.

like image 99
Džuris Avatar answered Feb 18 '26 02:02

Džuris