14

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?

Juliatzin
  • 18,455
  • 40
  • 166
  • 325

1 Answers1

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());
cmac
  • 3,123
  • 6
  • 36
  • 49