helloRoman5556
helloRoman5556

Reputation: 173

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?

Upvotes: 3

Views: 368

Answers (3)

Davit Zeynalyan
Davit Zeynalyan

Reputation: 8618

$list = Elements::where('list_id', $id)->with('visitors')->get();;

This code return Collection Instance. $collection->sortBy(...); also is Collection instance. For get array in Collection you must be use or ->toArray(), or ->all()

In your case you can use

$list = Elements::where('list_id', $id)->with('visitors')->get()->sortBy(function($t) {
    return $t->visitors->count();
})->toArray();

Upvotes: 0

Džuris
Džuris

Reputation: 2234

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.

Upvotes: 4

Alberto
Alberto

Reputation: 12909

You just need to call the ->all() Collection method, so

$list = Elements::where('list_id', $id)->with('visitors')->get()->sortBy(function($t)
      {
             return $t->visitors->count();
      }
)->all();

this differs to the ->toArray() method because it will also cast to array also the object inside the collection, and not only the colletion itself (actually ->all() won't cast anything, it will just return the elements inside the collection)

Upvotes: 1

Related Questions