DEV Community

Cover image for Mastering Laravel Collections Tutorial
Suresh Ramani
Suresh Ramani

Posted on • Originally published at techvblogs.com

Mastering Laravel Collections Tutorial

Learn how to work efficiently with arrays of data in Laravel using Collections. Our tutorial covers everything from the basics to advanced methods, including filtering, mapping, reducing, sorting, and grouping. With practical examples and clear explanations, you'll master Laravel Collections and improve your PHP development workflow.

What is a Collection in Laravel?

In Laravel, a Collection is an object-oriented and fluent interface for working with arrays of data. It provides a convenient way to filter, sort, map, and reduce data without the need for cumbersome loops or conditionals. Collections in Laravel are a wrapper around PHP arrays, providing a higher level of abstraction and a more expressive syntax for working with data. They can be used to manipulate database results, API responses, and any other type of structured data, making them a powerful tool for developers working on web applications with Laravel.

Creating Laravel collections

We can create a Laravel collection using two major ways:

Using the collect() method:

<?php

// using the collect() helper

public function test_helper_collection(){
    $array = ['Laravel', 'PHP'];

    return collect($array);
}
Enter fullscreen mode Exit fullscreen mode

In the code above, we declared an array and passed it to the collect() helper method which then created the Laravel collection.

Using a Collection class instance.

<?php

// using the Collection instance

public function test_collection_instance(){
    $array = ['Laravel','PHP'];

    return new Collection($array);
}
Enter fullscreen mode Exit fullscreen mode

In the code above, we instantiated the Illuminate\Support\Collection class and included our array. The class then converted the array to a collection.

List of Laravel Collection Functions

Here's a list of some of the most commonly used collection functions in Laravel:

  • all()
  • avg()
  • chunk()
  • collapse()
  • combine()
  • concat()
  • contains()
  • count()
  • countBy()
  • crossJoin()
  • diff()
  • diffAssoc()
  • each()
  • every()
  • except()
  • filter()
  • first()
  • flatten()
  • flip()
  • forget()
  • forPage()
  • get()
  • groupBy()
  • has()
  • implode()
  • intersect()
  • intersectByKeys()
  • isEmpty()
  • isNotEmpty()
  • keyBy()
  • keys()
  • last()
  • map()
  • max()
  • median()
  • merge()
  • min()
  • mode()
  • nth()
  • only()
  • partition()
  • pipe()
  • pluck()
  • pop()
  • prepend()
  • pull()
  • push()
  • put()
  • random()
  • reduce()
  • reject()
  • reverse()
  • search()
  • shift()
  • shuffle()
  • slice()
  • some()
  • sort()
  • sortBy()
  • sortByDesc()
  • splice()
  • split()
  • sum()
  • take()
  • tap()
  • toArray()
  • toJson()
  • transform()
  • union()
  • unique()
  • values()
  • when()
  • where()
  • whereBetween()
  • whereIn()
  • whereInstanceOf()
  • whereNotBetween()
  • whereNotIn()
  • whereNotNull()
  • wrap()

Let's look at some of the best and must-know Laravel Collection Methods:

1. all()

In Laravel Collection, the all() method is used to retrieve all the items of the collection as an array. This method can be useful when you want to convert a collection back into a plain PHP array.

Here's an example:

use Illuminate\Support\Collection;

// Create a new collection
$collection = new Collection([
    ['id' => 1, 'name' => 'John'],
    ['id' => 2, 'name' => 'Jane'],
    ['id' => 3, 'name' => 'Bob']
]);

// Retrieve all items as an array
$array = $collection->all();

// Output the array
print_r($array);
Enter fullscreen mode Exit fullscreen mode

In this example, we create a new collection containing three arrays with id and name keys. We then use the all() method to retrieve all the items of the collection as an array. Finally, we output the resulting array using print_r().

The output will be:

Array
(
    [0] => Array
        (
            [id] => 1
            [name] => John
        )

    [1] => Array
        (
            [id] => 2
            [name] => Jane
        )

    [2] => Array
        (
            [id] => 3
            [name] => Bob
        )
)
Enter fullscreen mode Exit fullscreen mode

As you can see, the all() method returns an array containing all the items of the collection. This can be useful if you need to pass the data to a function or method that requires a plain PHP array.

2. avg()

Avg method provided by Laravel Collection returns the average value. By default, it will provide an average of all the values in a collection. But, if a collection contains key => value pair, then you can provide key to the function and it will automatically calculate the average of all values to that key.

use Illuminate\Support\Collection;

// Create a new collection
$collection = new Collection([
    ['name' => 'John', 'score' => 80],
    ['name' => 'Jane', 'score' => 90],
    ['name' => 'Bob', 'score' => 70]
]);

// Calculate the average score
$averageScore = $collection->avg('score');

// Output the average score
echo 'The average score is: ' . $averageScore;
Enter fullscreen mode Exit fullscreen mode

In this example, we create a new collection containing three arrays with name and score keys. We then use the avg() method to calculate the average value of the score key in the collection. Finally, we output the resulting average score using echo.

The output will be:

The average score is: 80
Enter fullscreen mode Exit fullscreen mode

3. each()

In Laravel Collection, the each() method is used to iterate over the items in the collection and perform a callback function on each item. The purpose of this method is to execute some logic for each item in the collection without modifying the original collection.

Here's an example:

use Illuminate\Support\Collection;

// Create a new collection
$collection = new Collection([
    ['name' => 'John', 'score' => 80],
    ['name' => 'Jane', 'score' => 90],
    ['name' => 'Bob', 'score' => 70]
]);

// Iterate over each item in the collection and output the name
$collection->each(function ($item, $key) {
    echo $item['name'] . '<br>';
});
Enter fullscreen mode Exit fullscreen mode

In this example, we create a new collection containing three arrays with name and score keys. We then use the each() method to iterate over each item in the collection and output the name key of each item. The each() method takes a callback function as its argument, which receives the current item and key as its parameters.

The output will be:

John
Jane
Bob
Enter fullscreen mode Exit fullscreen mode

As you can see, the each() method executes the callback function for each item in the collection and performs some logic without modifying the original collection. This can be useful for performing various tasks on each item in the collection, such as outputting values, logging data, or updating external systems.

4. chunk()

chunk() method is used to split the Laravel Collection into multiple chunks of a given size.

use Illuminate\Support\Collection;

// Create a new collection with 10 items
$collection = new Collection([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);

// Split the collection into chunks of 3 items each
$chunks = $collection->chunk(3);

// Output each chunk
$chunks->each(function ($chunk, $key) {
    echo "Chunk $key: " . implode(', ', $chunk->toArray()) . "<br>";
});
Enter fullscreen mode Exit fullscreen mode

In this example, we create a new collection containing ten items. We then use the chunk() method to split the collection into chunks of three items each. Finally, we use the each() method to output each chunk as a comma-separated list.

The output will be:

Chunk 0: 1, 2, 3
Chunk 1: 4, 5, 6
Chunk 2: 7, 8, 9
Chunk 3: 10
Enter fullscreen mode Exit fullscreen mode

5. contains()

In Laravel Collection, the contains() method is used to determine if the collection contains a given item or key-value pair. The method returns true if the item or key-value pair is found in the collection and false otherwise.

Here's an example:

use Illuminate\Support\Collection;

// Create a new collection
$collection = new Collection([
    ['name' => 'John', 'score' => 80],
    ['name' => 'Jane', 'score' => 90],
    ['name' => 'Bob', 'score' => 70]
]);

// Check if the collection contains an item with score 80
$containsItem = $collection->contains(function ($item, $key) {
    return $item['score'] === 80;
});

// Check if the collection contains an item with name 'Alice'
$containsKeyValue = $collection->contains('name', 'Alice');

// Output the results
echo 'Contains item with score 80: ' . ($containsItem ? 'Yes' : 'No') . '<br>';
echo 'Contains key-value pair with name "Alice": ' . ($containsKeyValue ? 'Yes' : 'No');
Enter fullscreen mode Exit fullscreen mode

In this example, we create a new collection containing three arrays with name and score keys. We then use the contains() method to check if the collection contains an item with a score key of 80. We also use the contains() method to check if the collection contains a key-value pair with a name key of Alice. The contains() method takes a callback function or key-value pair as its argument, depending on whether you want to search for an item or a key-value pair.

The output will be:

Contains item with score 80: Yes
Contains key-value pair with name "Alice": No
Enter fullscreen mode Exit fullscreen mode

6. count()

The Count() method gives the total number of items in the given Laravel Collection.

use Illuminate\Support\Collection;

// Create a new collection
$collection = new Collection([1, 2, 3, 4, 5]);

// Get the number of items in the collection
$count = $collection->count();

// Output the result
echo "The collection has $count items.";
Enter fullscreen mode Exit fullscreen mode

7. countBy()

The countBy() method gives the count of an item's occurrences in a given Laravel Collection in an array.

use Illuminate\Support\Collection;

// Create a new collection
$collection = new Collection(['apple', 'banana', 'cherry', 'date', 'apple']);

// Get the count of each item in the collection
$countBy = $collection->countBy();

// Output the result
foreach ($countBy as $item => $count) {
    echo "$item: $count<br>";
}
Enter fullscreen mode Exit fullscreen mode

In this example, we create a new collection containing five items, including two instances of the string 'apple'. We then use the countBy() method to get a count of each item in the collection. The resulting array will have keys equal to the distinct items in the collection, and values equal to the number of occurrences of each item. Finally, we output the result using a foreach loop.

The output will be:

apple: 2
banana: 1
cherry: 1
date: 1
Enter fullscreen mode Exit fullscreen mode

8. filter()

The filter() method is one of the most popular and useful Laravel Collection methods. It allows you to filter your collection using the passed callback function. It returns the new collection with filtered items and does not change the original collection.

The callback function is provided with a key and value as its parameters which you can utilize to create the filter condition.

use Illuminate\Support\Collection;

// Create a new collection
$collection = new Collection([1, 2, 3, 4, 5]);

// Filter the collection to only include even numbers
$filtered = $collection->filter(function ($item) {
    return $item % 2 == 0;
});

// Output the result
foreach ($filtered as $item) {
    echo "$item<br>";
}
Enter fullscreen mode Exit fullscreen mode

The output will be:

2
4
Enter fullscreen mode Exit fullscreen mode

9. get()

The get() method in Laravel Collection is used to retrieve an item from the collection by its key or index. It returns the value of the item if it exists, or a default value if it does not.

Here's an example:

use Illuminate\Support\Collection;

// Create a new collection
$collection = new Collection([
    'name' => 'John Doe',
    'email' => 'johndoe@example.com',
    'phone' => '555-1234'
]);

// Get the value of the 'email' key
$email = $collection->get('email');

// Get the value of the 'age' key, or a default value if it does not exist
$age = $collection->get('age', 30);

// Output the results
echo "Email: $email<br>";
echo "Age: $age<br>";
Enter fullscreen mode Exit fullscreen mode

The output will be:

Email: johndoe@example.com
Age: 30
Enter fullscreen mode Exit fullscreen mode

10. search()

The search() method in Laravel Collection is used to search the collection for the first occurrence of a given value and return its key. If the value is not found, the method returns false.

Here's an example:

use Illuminate\Support\Collection;

// Create a new collection
$collection = new Collection([2, 4, 6, 8, 10]);

// Search for the first occurrence of the value 6
$key = $collection->search(6);

// Output the result
echo "Key of 6: $key<br>";
Enter fullscreen mode Exit fullscreen mode

The output will be:

Key of 6: 2
Enter fullscreen mode Exit fullscreen mode

11. groupBy()

The groupBy() method in Laravel Collection is used to group the items in the collection by a given key or callback function.

Here's an example:

use Illuminate\Support\Collection;

// Create a new collection of people
$people = new Collection([
    ['name' => 'John', 'age' => 25],
    ['name' => 'Jane', 'age' => 30],
    ['name' => 'Bob', 'age' => 25],
    ['name' => 'Alice', 'age' => 30]
]);

// Group the people by age
$grouped = $people->groupBy('age');

// Output the result
$grouped->each(function($group) {
    echo $group->pluck('name')->implode(', ') . "<br>";
});
Enter fullscreen mode Exit fullscreen mode

The output will be:

John, Bob
Jane, Alice
Enter fullscreen mode Exit fullscreen mode

As you can see, the groupBy() method is a powerful tool for grouping and organizing data in a collection based on a given key or criteria.

12. max()

The max() method in Laravel Collection is used to get the maximum value of a given key or attribute in the collection.

use Illuminate\Support\Collection;

// Create a new collection of numbers
$numbers = new Collection([3, 6, 1, 9, 2]);

// Get the maximum number in the collection
$max = $numbers->max();

// Output the result
echo "The maximum number is: $max";
Enter fullscreen mode Exit fullscreen mode

The output will be:

The maximum number is: 9
Enter fullscreen mode Exit fullscreen mode

13. pluck()

The pluck() method in Laravel Collection is used to get an array of values from a single column or attribute of a collection.

use Illuminate\Support\Collection;

// Create a new collection of cars
$cars = new Collection([
    ['make' => 'Toyota', 'model' => 'Corolla'],
    ['make' => 'Honda', 'model' => 'Accord'],
    ['make' => 'Ford', 'model' => 'Mustang']
]);

// Get an array of car makes
$makes = $cars->pluck('make');

// Output the result
echo "The car makes are: " . implode(', ', $makes);
Enter fullscreen mode Exit fullscreen mode

The output will be:

The car makes are: Toyota, Honda, Ford
Enter fullscreen mode Exit fullscreen mode

14. forget()

forget() is a Laravel collection method that simply removes the given key and its value from all the items in the collection.

use Illuminate\Support\Collection;

// Create a new collection of fruit prices
$fruitPrices = new Collection([
    'apple' => 0.5,
    'banana' => 0.25,
    'orange' => 0.75,
    'pear' => 0.4
]);

// Remove the price of oranges from the collection
$fruitPrices->forget('orange');

// Output the result
echo "The updated fruit prices are: " . $fruitPrices->toJson();
Enter fullscreen mode Exit fullscreen mode

The output will be:

The updated fruit prices are: {"apple":0.5,"banana":0.25,"pear":0.4}
Enter fullscreen mode Exit fullscreen mode

15. toArray()

The toArray() method in Laravel Collection is used to convert a collection into a plain PHP array.

use Illuminate\Support\Collection;

// Create a new collection of numbers
$numbers = new Collection([1, 2, 3, 4, 5]);

// Convert the collection to an array
$array = $numbers->toArray();

// Output the result
print_r($array);
Enter fullscreen mode Exit fullscreen mode

The output will be:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)
Enter fullscreen mode Exit fullscreen mode

16. sortBy()

The sortBy() method in Laravel Collection is used to sort a collection by a given key or callback.

use Illuminate\Support\Collection;

// Create a new collection of products
$products = new Collection([
    ['name' => 'Keyboard', 'price' => 30],
    ['name' => 'Mouse', 'price' => 20],
    ['name' => 'Monitor', 'price' => 200],
    ['name' => 'Speakers', 'price' => 50]
]);

// Sort the collection by price
$sorted = $products->sortBy('price');

// Output the result
$sorted->each(function($product) {
    echo $product['name'] . ' - ' . $product['price'] . '<br>';
});
Enter fullscreen mode Exit fullscreen mode

The output will be:

Mouse - 20
Keyboard - 30
Speakers - 50
Monitor - 200
Enter fullscreen mode Exit fullscreen mode

17. toJson()

The toJson() method in Laravel Collection is used to convert a collection into a JSON string. It can be useful when passing collection data to a JavaScript frontend or to simply return data in JSON format from an API endpoint.

Here's an example:

$collection = collect([
    ['name' => 'John', 'age' => 32],
    ['name' => 'Jane', 'age' => 28]
]);

$json = $collection->toJson();

// Output: [{"name":"John","age":32},{"name":"Jane","age":28}]
Enter fullscreen mode Exit fullscreen mode

18. whereBetween()

whereBetween() is a method available in Laravel Collection which allows you to filter the collection items based on a range of values. It takes two parameters: the name of the attribute to filter and an array of two values representing the range.

Here's an example:

$collection = collect([
    ['name' => 'John', 'age' => 32],
    ['name' => 'Jane', 'age' => 28],
    ['name' => 'Doe', 'age' => 45]
]);

$filtered = $collection->whereBetween('age', [30, 40]);

// Output: 
/*
    [
        ['name' => 'John', 'age' => 32],
        ['name' => 'Jane', 'age' => 28]
    ]
*/
Enter fullscreen mode Exit fullscreen mode

19. whereIn()

whereIn() is a method available in Laravel Collection that allows you to filter the collection items based on an array of values. It takes two parameters: the name of the attribute to filter and an array of values to match against.

Here's an example:

$collection = collect([
    ['name' => 'John', 'age' => 32],
    ['name' => 'Jane', 'age' => 28],
    ['name' => 'Doe', 'age' => 45]
]);

$filtered = $collection->whereIn('name', ['John', 'Jane']);

// Output: 
/*
    [
        ['name' => 'John', 'age' => 32],
        ['name' => 'Jane', 'age' => 28]
    ]
*/
Enter fullscreen mode Exit fullscreen mode

20. isEmpty()

isEmpty() is a method available in Laravel Collection that allows you to check if a collection is empty. It returns a boolean value indicating whether the collection is empty or not.

Here's an example:

$collection = collect([]);

$is_empty = $collection->isEmpty();

// Output: true
Enter fullscreen mode Exit fullscreen mode

21. sum()

sum() is a method available in Laravel Collection that allows you to calculate the sum of a specific key's values in a collection. It returns the sum of the values in the collection.

Here's an example:

$collection = collect([
    ['product' => 'Desk', 'price' => 200],
    ['product' => 'Chair', 'price' => 100],
    ['product' => 'Bookcase', 'price' => 150],
]);

$total_price = $collection->sum('price');

// Output: 450
Enter fullscreen mode Exit fullscreen mode

22. map()

map() is a method available in Laravel Collection that allows you to modify each item in the collection using a callback function. It returns a new collection containing the modified items.

Here's an example:

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

$mapped_collection = $collection->map(function ($item) {
    return $item * 2;
});

// Output: [2, 4, 6, 8, 10]
Enter fullscreen mode Exit fullscreen mode

23. only()

only() is a method available in Laravel Collection that allows you to filter the collection to only the specified keys. It returns a new collection containing only the specified keys.

Here's an example:

$collection = collect([
    'name' => 'John',
    'age' => 30,
    'gender' => 'male',
    'city' => 'New York'
]);

$filtered_collection = $collection->only(['name', 'age']);

// Output: ['name' => 'John', 'age' => 30]
Enter fullscreen mode Exit fullscreen mode

24. pop()

pop() is a method available in Laravel Collection that allows you to remove and return the last item from the collection.

Here's an example:

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

$last_item = $collection->pop();

// Output: [1, 2, 3, 4]
// $last_item = 5
Enter fullscreen mode Exit fullscreen mode

25. random()

random() is a method available in Laravel Collection that allows you to retrieve a random item from the collection.

Here's an example:

$collection = collect(['apple', 'banana', 'orange', 'mango', 'pear']);

$random_item = $collection->random();

// Output: 'orange' (or any other random item from the collection)
Enter fullscreen mode Exit fullscreen mode

Conclusion

In conclusion, Laravel Collection is a powerful and versatile feature in the Laravel framework that provides developers with a wide range of useful methods to work with arrays of data. From simple operations like counting and filtering, to more advanced functions like grouping and sorting, Laravel Collection makes it easy to manipulate data in elegant and efficient ways.

By mastering the various methods available in Laravel Collection, developers can streamline their code, improve performance, and create more flexible and dynamic applications. Whether you're building a simple blog or a complex enterprise application, understanding how to use Laravel Collection effectively is an essential skill for any Laravel developer.

Overall, Laravel Collection is a valuable tool that can help developers save time and reduce the complexity of their code. By incorporating it into your development workflow, you can write cleaner, more efficient code and build better Laravel applications.

Top comments (0)