Laravel 11 for Beginners: Collections for Data Handling

Arlind Musliu Portrait
Arlind Musliu

January 11, 2024 · 3 min read · 25 views

Laravel Blogpost Image

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...
]);

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 out posts with less than 100 views:

<?php

$popularPosts = $posts->filter(function ($post) {
    return $post['views'] >= 100;
});

Sorting Data

To sort your posts by their title in descending order:

$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

$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

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

Collections and Eloquent

When using Eloquent, Laravel's ORM, the results returned from queries are automatically Collection instances, giving you immediate access to all collection methods:

<?php

$latestPosts = Post::latest()->get(); // Returns a Collection of Post models

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


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!