Sling Academy
Home/PHP/Collections in Laravel: A Deep Dive with Examples

Collections in Laravel: A Deep Dive with Examples

Last updated: January 16, 2024

Introduction

Laravel’s collection class provides a fluent, convenient wrapper for working with arrays of data. In this tutorial, we will explore how you can utilize collections in the Laravel framework by looking at a variety of examples. This guide will take you from the basics to more advanced uses, showing how collections can make your code more readable, maintainable, and efficient.

Basic Usage of Collections

To start with collections, let’s first understand how to create them. You can create a collection instance from an array using the collect helper function:

$collection = collect([1, 2, 3, 4, 5]);

Once you have a collection, you have a variety of methods at your disposal. Here’s an example of using the each method to iterate over items:

$collection->each(function ($item, $key) {
    echo $item;
});
// Output: 12345

You can also perform operations like map, filter, and reduce that allow you to manipulate the collection data easily.

Transforming Collections

The map method applies a callback function to each item and returns a new collection with the items transformed:

$multiplied = $collection->map(function ($item, $key) {
    return $item * 2;
});
// Output: [2, 4, 6, 8, 10]

Filtering is another powerful feature. For instance, the filter method removes items based on a condition:

$filtered = $collection->filter(function ($value) {
    return $value > 3;
});
// Output: [4, 5]

Collection Keys and Values

You can also work with the keys of the collection using methods such as keys to obtain the collection’s keys:

$collection = collect([
    'name' => 'John',
    'email' => '[email protected]'
]);

$keys = $collection->keys();
// Output: ['name', 'email']

To get the values without keys:

$values = $collection->values();
// Output: ['John', '[email protected]']

Advanced Collection Methods

Laravel collections offer more advanced methods, such as groupBy, that allow you to group items by a given key:

$collection = collect([
    ['product' => 'Apples', 'price' => 50],
    ['product' => 'Oranges', 'price' => 60],
    ['product' => 'Apples', 'price' => 70]
]);

$grouped = $collection->groupBy('product');

// Output: ['Apples' => [[...], [...]], 'Oranges' => [[...]]]

Combine them with other methods like sum can give powerful insights:

$totalPrices = $grouped->map(function ($item, $key) {
    return $item->sum('price');
});
// Output: ['Apples' => 120, 'Oranges' => 60]

Working with JSON

Collections can easily be converted to JSON for use with APIs or JavaScript:

$collection = collect(['name' => 'John', 'email' => '[email protected]']);
$json = $collection->toJson();
// Output: '{"name":"John","email":"[email protected]"}'

Lazy Collections

For dealing with extremely large datasets, you can take advantage of lazy collections introduced in Laravel. They allow you to work with a very large amount of data efficiently:

$lazyCollection = 
    \\\Illuminate\\\Support\\\LazyCollection::make(function () {
        for ($i = 0; $i < 1000000; $i++) {
            yield $i;
        }
});

// Use the collection without loading all elements into memory

Conclusion

Throughout this tutorial, we’ve explored various functionalities of Laravel collections from simple iteration to complex transformations and lazy loading. Understanding these concepts helps write cleaner and more efficient code, leveraging the full power of Laravel’s collections for elegant data handling.

Next Article: How to Send Email in Laravel: The Right Way

Previous Article: How to store and read data from cache in Laravel

Series: Laravel & Eloquent Tutorials

PHP

You May Also Like

  • Pandas DataFrame.value_counts() method: Explained with examples
  • Constructor Property Promotion in PHP: Tutorial & Examples
  • Understanding mixed types in PHP (5 examples)
  • Union Types in PHP: A practical guide (5 examples)
  • PHP: How to implement type checking in a function (PHP 8+)
  • Symfony + Doctrine: Implementing cursor-based pagination
  • Laravel + Eloquent: How to Group Data by Multiple Columns
  • PHP: How to convert CSV data to HTML tables
  • Using ‘never’ return type in PHP (PHP 8.1+)
  • Nullable (Optional) Types in PHP: A practical guide (5 examples)
  • Explore Attributes (Annotations) in Modern PHP (5 examples)
  • An introduction to WeakMap in PHP (6 examples)
  • Type Declarations for Class Properties in PHP (5 examples)
  • Static Return Type in PHP: Explained with examples
  • PHP: Using DocBlock comments to annotate variables
  • PHP: How to ping a server/website and get the response time
  • PHP: 3 Ways to Get City/Country from IP Address
  • PHP: How to find the mode(s) of an array (4 examples)
  • PHP: Calculate standard deviation & variance of an array