Currently Available: Need a skilled Software Developer for your next project?
Categories
Laravel

When to Use Laravel Collections vs. Plain Arrays

When you write PHP in Laravel, you can store values in a native array or use a Laravel collection. A collection is an object with methods for changing and inspecting its items. Use an array for simple storage or when code requires an array. Use a collection when its chainable methods make several steps easier to follow.

Both hold data in memory: a PHP array is a built-in ordered map, and a collection adds Laravel methods for working with that data. Knowing when to use each helps you choose the right type for your code and avoid expecting a collection to retrieve database records or handle large streams on its own.

What collections add to array processing

PHP arrays already let you loop through items, look them up, and transform them with language syntax and built-in functions such as array_map and array_filter. A Laravel collection provides a consistent set of methods, including map, filter, reject, pluck, and groupBy. Each method returns a collection, so you can call another method on the result. Laravel’s collect() helper turns an array into a collection.

For example, given a $minimumPrice threshold, both versions below keep prices at or above that threshold and then apply a discount:

$prices = [10, $minimumPrice, 30, 40];

$discountedWithArray = array_map(
    fn (int $price) => $price * 0.9,
    array_filter($prices, fn (int $price) => $price >= $minimumPrice),
);

$discountedWithCollection = collect($prices)
    ->filter(fn (int $price) => $price >= $minimumPrice)
    ->map(fn (int $price) => $price * 0.9)
    ->values()
    ->all();

The collection code shows the steps in order: filter the prices, apply the discount, reset the keys, and return an array. filter() preserves the original keys, so values() gives the results consecutive numeric keys. The array code uses PHP’s built-in functions to do the same filtering and discounting.

Use a collection when chaining several transformations makes the steps easier to follow. Use an array for a simple lookup or a small set of values that needs no transformation; a collection would add an object and methods without making the code clearer.

What collections do not replace

A collection does not replace PHP’s array type. PHP arrays are ordered maps with integer or string keys. PHP also provides its own syntax and functions for working with arrays. If a function or interface requires an array, pass it an array. A collection works only if the function or interface also accepts that type. Check the interface’s requirements when it accepts other iterable types.

Laravel provides two common ways to turn a collection into an array. all() returns the array stored in the collection. toArray() also converts the collection’s values to arrays, including any Eloquent models. Use all() when the receiving code expects model objects inside an array. Use toArray() when it expects the model data as arrays. Laravel describes these methods in its collection API.

A collection filters values after PHP retrieves them. If a query returns every matching row and a collection then filters those results, PHP has already received all those rows from the database. For large results, use a query or iteration strategy that avoids loading everything into memory at once.

Laravel’s LazyCollection lets code process items one at a time as it iterates. A regular collection holds all its items in memory. Laravel’s documentation compares User::all()->filter(...), which loads all 10,000 models in its example, with User::cursor()->filter(...), which uses a lazy collection and keeps one model in memory at a time. The example shows the difference between eager and lazy retrieval. It does not provide a general performance benchmark. See Laravel’s lazy collection documentation.

A regular collection can change. Methods such as map() return a new collection, while transform() and forget() modify the collection they act on. Check what a method does before assuming the original collection stays unchanged.

When Eloquent returns a collection

When Eloquent returns multiple database models, such as from get() or a relationship, it returns an Eloquent collection. This type builds on Laravel’s base collection and adds methods for working with model results. Those methods are useful when you need to transform the models Eloquent retrieved.

For example, if a query has already retrieved users, a collection can extract their email addresses:

$emails = User::where('active', true)
    ->get()
    ->pluck('email');

The query builder selects and retrieves the records. The collection’s pluck() method then extracts a value from each model Eloquent returned. This distinction makes clear that pluck() works on models in memory; it does not filter records in the database. Laravel describes the extra methods in its Eloquent collections documentation.

Choose by the work and the required type

Use an array to store or pass simple values, use PHP’s array-specific operations, or meet an interface that requires an array. Use a collection when Laravel’s chainable methods make several transformations clearer, or when you work with Eloquent results and need collection methods designed for models.

If performance matters, measure your actual workload. Do not assume arrays run faster or collections use less memory. The cited documentation describes the APIs and the memory difference between eager and lazy retrieval, but it does not show that arrays or regular collections are generally faster for equivalent transformations.

What I'm building

Delegate tasks. Get software.

Give Vroni a GitHub issue, bug report, spec, or rough idea. It reads the repo, plans the change, writes code, runs checks, and works toward a review-ready pull request.

Take a look at vroni.com

Email updates

Usually a new article and a few links I found interesting.

No spam. Unsubscribe with one click.

Leave a Reply

Your email address will not be published. Required fields are marked *