Juliatzin
Juliatzin

Reputation: 19705

Difference between all() and toArray() in Laravel 5

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?

Upvotes: 15

Views: 11681

Answers (1)

cmac
cmac

Reputation: 3268

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

Upvotes: 24

Related Questions