Laravel Collections: Methods, Lazy Collections, and Real Examples

January 11, 2024 · 5 min read

2026 UPDATE - LARAVEL 13
We’re excited to announce that we have updated all of our blog post examples to reflect the new Laravel 13 version! Our previous examples were based on Laravel 10, but with the release of Laravel 13, we wanted to ensure that our readers have access to the most up-to-date information and examples.
The Power of Fluent Data Handling with Collections
When working with arrays of data in your Laravel application, you might often find yourself writing loops and conditional statements to manipulate this data. Laravel introduces a more elegant solution: Collections. Collections are one of the most powerful and flexible features of Laravel, providing a fluent, convenient wrapper for working with arrays of data.
What are Laravel Collections?
A Collection is a PHP object that wraps around an array, allowing you to chain array operations in a more readable and less error-prone way. Collections are not just about convenience; they provide a vast arsenal of methods for traversing, sorting, filtering, and modifying your data sets.
Creating Collections
In Laravel, Collections are automatically returned when you fetch results from Eloquent queries. However, you can create a collection instance from any PHP array using the collect() helper function:
$posts = collect([
['id' => 1, 'title' => 'The first post', 'views' => 100],
['id' => 2, 'title' => 'The second post', 'views' => 50],
// More posts...
]);However, Collections are automatically returned when you fetch results from Eloquent queries.
use App\Models\Post;
public function index()
{
// Retrieve all posts from the database
$posts = Post::all();
}Now, $posts is a Collection instance containing your blog post data.
Manipulating Collections
Collections provide a suite of methods that you can use to manipulate the underlying array. Let’s explore some common operations you might perform on your blog’s data.
Filtering Data
Imagine you want to filter posts with more than 10,000 views:
$posts = collect([
['id' => 1, 'title' => 'The first post', 'views' => 100],
['id' => 2, 'title' => 'The second post', 'views' => 50],
// More posts...
]);
$popularPosts = $posts->filter(function ($post) {
return $post['views'] >= 10000;
});Sorting Data
To sort your posts by their title in descending order:
$posts = collect([
['id' => 1, 'title' => 'The first post', 'views' => 100],
['id' => 2, 'title' => 'The second post', 'views' => 50],
// More posts...
]);
$sortedPosts = $posts->sortByDesc('title');Mapping Over Data
If you want to apply a transformation to each post, for example appending the string "(Updated)" to each title:
$posts = collect([
['id' => 1, 'title' => 'The first post', 'views' => 100],
['id' => 2, 'title' => 'The second post', 'views' => 50],
// More posts...
]);
$updatedPosts = $posts->map(function ($post) {
return array_merge($post, ['title' => $post['title'] . ' (Updated)']);
});Chaining Methods
One of the most powerful features of collections is method chaining, which allows you to perform multiple operations in a single, fluent expression:
$posts = collect([
['id' => 1, 'title' => 'The first post', 'views' => 100],
['id' => 2, 'title' => 'The second post', 'views' => 50],
// More posts...
]);
$featuredPosts = $posts
->sortByDesc('title')
->take(5)
->map(function ($post) {
return $post['title'];
});This chain sorts the posts by title, takes the top 5, and then transforms the collection only to include the post titles.
Eloquent Collections
When using Eloquent, Laravel’s ORM, the results returned from queries are automatically Collection instances, giving you immediate access to all collection methods:
use App\Models\Post;
public function index()
{
// Retrieve all posts from the database
$posts = Post::all();
}We already explained how to use collections to manipulate an array. Let’s see how we can do that using Eloquent’s query builder methods and respond with collections.
Filtering Data
Imagine you want to filter posts with more than 10,000 views:
use App\Models\Post;
public function index()
{
// Retrieve all posts from the database
$posts = Post::all();
// Filter posts with more than 10,000 views
$popularPosts = Post::where('views', '>=', 10000)->get();
}Sorting Data
To sort your posts by their title in descending order:
use App\Models\Post;
public function index()
{
// Sort posts by title in descending order
$sortedPosts = Post::orderBy('title', 'desc')->get();
}Mapping Over Data
If you want to apply a transformation to each post, for example appending the string "(Updated)" to each title. Since this involves modifying the collection rather than querying the database, you'll retrieve the collection first and then update the titles:
use App\Models\Post;
public function index()
{
// Retrieve all posts from the database
$posts = Post::all();
// add (Updated) to each post title
$updatedPosts = $posts->each(function ($post) {
$post->title .= ' (Updated)';
$post->save(); // Save the updated title to the database
});
}Chaining Methods
For this operation, you can use a combination of orderBy, take, and get to retrieve the posts, and then pluck to retrieve only the titles.
use App\Models\Post;
public function index()
{
// Get the title of the 5 latest posts
$featuredPosts = Post::orderBy('title', 'desc')
->take(5)
->get()
->pluck('title');
}In this chain:
orderBy('title', 'desc')sorts the posts by the 'title' column in descending order.take(5)limits the results to the first 5 records.get()retrieves the records from the database.pluck('title')extracts only the 'title' attribute from each record in the resulting collection.

Lazy Collections: Memory-Efficient Data Processing
Standard Collections load all data into memory at once. For small to medium datasets this is fine, but when processing thousands of database rows or large files it can exhaust available memory. LazyCollection solves this by using PHP generators to stream items one at a time, so only a single item is held in memory at any given moment.
The most common entry point is Eloquent’scursor() method. Instead of loading all matching rows into a Collection, it returns a LazyCollection that fetches rows one by one from the database:
use App\Models\Post;
// Processes 100,000 posts without loading them all into memory
Post::cursor()->each(function (Post $post) {
// process each post individually
});
// You can still chain collection methods on a LazyCollection
$titles = Post::cursor()
->filter(fn ($post) => $post->views > 1000)
->map(fn ($post) => $post->title)
->values();You can also create a LazyCollection manually from any iterable, including generators. Use LazyCollection whenever you are iterating over large Eloquent result sets, processing CSV exports, or streaming log files. Any scenario where loading everything at once would risk a memory limit error.
Common Collection Methods: Quick Reference
These are the methods you will reach for most often. All of them work on both standard Collection and Eloquent Collection instances:
map()- transform each item and return a new collectionfilter()- keep only items that pass a truth testreduce()- collapse the collection to a single value (e.g. sum, concatenation)pluck()- extract a single key from every itemgroupBy()- group items by a key or callbacksortBy()/sortByDesc()- sort by a key or callbackfirst()/last()- retrieve the first or last item matching an optional conditioncontains()- check whether the collection contains a given value or key/value pairunique()- remove duplicate itemsflatten()- collapse a multi-dimensional collection into a single levelchunk()- split the collection into smaller collections of a given size
Conclusion
Laravel Collections turn the task of data manipulation into a simple, fluent, and enjoyable process. They enable you to write cleaner, more expressive code when dealing with arrays of data in your blog application. Whether you’re filtering search results, sorting posts by popularity, or collecting statistics, Collections have got you covered.
Upcoming Articles in the Series
This article is part of our series Laravel for Beginners: A Step-by-Step Guide to Learn the Concepts.
Bring Your Ideas to Life 🚀
If you need help with a Laravel project let’s get in touch.
Lucky Media is proud to be recognized as a leading Laravel Development Agency
Technologies

Stay up-to-date
Be updated with all news, products and tips we share!

