15

When I manage a collection that I need to convert to an array, I usually use toArray(). But I can also use all(). I'm not aware of the diference of those 2 function...

Anybody knows?

1
  • 2
    all() will return you Eloquent Objects where as toArray() will return you Associative Arrays. Commented Apr 8, 2017 at 13:56

1 Answer 1

24

If it's a collection of Eloquent models, the models will also be converted to arrays with toArray()

    $col->toArray();

With all it will return an array of Eloquent models without converting them to arrays.

    $col->all();

The toArray method converts the collection into a plain PHP array. If the collection's values are Eloquent models, the models will also be converted to arrays: toArray()

all() returns the items in the collection

/**
 * Get all of the items in the collection.
 *
 * @return array
 */
public function all()
{
    return $this->items;
}

toArray() returns the items of the collection and converts them to arrays if Arrayable:

/**
 * Get the collection of items as a plain array.
 *
 * @return array
 */
public function toArray()
{
    return array_map(function ($value) {
        return $value instanceof Arrayable ? $value->toArray() : $value;
    }, $this->items);
}

For example: Grab all your users from database like this:

$users = User::all();

Then dump them each way and you will see difference:

dd($users->all());

And with toArray()

dd($users->toArray());
Sign up to request clarification or add additional context in comments.

3 Comments

Are there any changes across versions 7-9? Is the same logic applied to nested objects?
I'm not sure, I'll have to test it out and see.
@s3c Across versions 7-9 the functionality has not changed. The logic of toArray() also converts nested objects to arrays.

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.