Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 827
Juliatzin Avatar asked Apr 07 '17 21:04

Juliatzin


People also ask

What is the use of toArray () in laravel?

In many cases, the toArray() method on Model the class is called under the hood to serialize your model. To customize for all your models what should get returned for the translatable attributes you could wrap the Spatie\Translatable\HasTranslations trait into a custom trait and overrides the toArray() method.

What are collections in laravel?

Laravel collection is a useful feature of the Laravel framework. A collection works like a PHP array, but it is more convenient. The collection class is located in the Illuminate\Support\Collection location. A collection allows you to create a chain of methods to map or reduce arrays.

What is pluck in laravel?

Laravel Pluck() is a Laravel Collections method used to extract certain values from the collection. You might often would want to extract certain data from the collection i.e Eloquent collection.

What is first () in laravel?

The Laravel Eloquent first() method will help us to return the first record found from the database while the Laravel Eloquent firstOrFail() will abort if no record is found in your query. So if you need to abort the process if no record is found you need the firstOrFail() method on Laravel Eloquent.


1 Answers

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());
like image 164
cmac Avatar answered Oct 26 '22 11:10

cmac