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?
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.
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.
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.
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.
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With