3

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?

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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)

Comments

0
$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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.