Laravel 11 for Beginners: Collections for Data Handling

Arlind Musliu Portrait
Arlind Musliu

January 11, 2024 · 4 min read · 288 views

Laravel Collections Example

2024 UPDATE - LARAVEL 11

We're excited to announce that we have updated all of our blog post examples to reflect the new Laravel 11 version! Our previous examples were based on Laravel 10, but with the release of Laravel 11, 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:

<?php

$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.

<?php

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:

<?php

$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:

<?php

$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:

<?php

$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:

<?php

$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.

laravel pipelines

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:

<?php

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:

<?php

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:

<?php

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:

<?php

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.

<?php

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.

Laravel best PHP framework

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

  1. Laravel for Beginners: PHPUnit and PEST Tests

  2. Laravel for Beginners: Blade and Breeze

  3. Laravel for Beginners: Service Providers

This article is part of our series Laravel 11 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 Top Laravel Development Agency

Arlind Musliu Portrait
Arlind Musliu

Cofounder and CFO of Lucky Media

Technologies:

Laravel
Heading Pattern

Related Posts

Stay up to date

Be updated with all news, products and tips we share!