Laravel Collection provides a fluent API for working with arrays of data. and they’re used almost everywhere in Laravel and rightly so. Collections offer a ton of useful methods to handle arrays. If you have worked with just PHP in the past, then you would know the trouble of implementing some of the standard functions in Arrays. In this article, we’ll take a look at the ten most useful Laravel Collection methods.

Creating a New Laravel Collection

You can create a collection either by instantiating the Illuminate\Support\Collection Class or using the collect() helper method.

Using the collect() helper

$myCOllection = collect([1, 1, 2, 3, 5, 8]);

Using Illuminate\Support\Collection class:

<?php

namespace app\Http\Controllers;

use Illuminate\Support\Collection;

class UserController extends Controller
{
    /**
     * Create a new collection with a Collection class instance.
     */
    public function storeCollection()
    {
        $myCollection = new Collection([1, 1, 2, 3, 5, 8]);
        dd($myCollection); // [1, 1, 2, 3, 5, 8]
    }
}

There are no perceived performance gains over using one over the other. Whether you use the helper method (collect()) or the Collection class, it is totally up to you and both are standard practices.

10 Useful Laravel Collection Methods

Now that we’ve learned how easy it is to create and use collections, let’s see some of the excellent methods that we can use. There are more than 100 collection methods available, but here are some of the most useful ones.

all()

The all() method is one of the widely known collection methods as most developers often use it to fetch all records from a database using Eloquent. The all() method returns all of the elements of the underlying array. For example, in an Eloquent Model you often do:

//Eloquent always returns a collection object when returning multiple objects
$users = User::all()
dd($users)

//OR

collect([1, 1, 2, 3, 5, 8])->all();

// [1, 1, 2, 3, 5, 8]

duplicates()

If you have duplicate items in your array that you might want to weed out, use the duplicates() method. This method can be used to find duplicate elements in a collection.

//Using Laravel Helper Method
$collection = collect([1, 1, 2, 3, 5, 8]);

$collection->duplicates();

// [1 => '1']

//Using the Class method

$collection = new Collection([1, 1, 2, 3, 5, 8]);

$collection->duplicates();

// [1 => '1']

However, if you have a collection of objects then you can pass the key of the object against which you want to check for duplicates.

//Using Laravel Helper

$cars = collect([
    ['model' => 'A8', 'Brand' => 'Audi'],
    ['model' => 'W150', 'Brand' => 'Mercedes'],
    ['model' => 'W150', 'Brand' => 'Maruti'],
])

$cars->duplicates('model');

// [2 => 'W150']

//Using the Illuminate\Support\Collection Class

$cars = new Collection([
    ['model' => 'A8', 'Brand' => 'Audi'],
    ['model' => 'W150', 'Brand' => 'Mercedes'],
    ['model' => 'W150', 'Brand' => 'Maruti'],
])

$cars->duplicates('model');

// [2 => 'W150']

For Eloquent models, the duplicate() method works similarly. Let’s fetch all the users with the same email address from the database.

$usersWithSameEmail = User::duplicate('email');

first()

Collection::first() or collection()->first() returns the first element in the array.

//Using Laravel Helper

$cars = collect([
    ['model' => 'A8', 'Brand' => 'Audi'],
    ['model' => 'W150', 'Brand' => 'Mercedes'],
    ['model' => 'W150', 'Brand' => 'Maruti'],
])

$cars->first();

// ['model' => 'A8', 'Brand' => 'Audi']

//Using the Illuminate\Support\Collection Class

$cars = new Collection([
    ['model' => 'A8', 'Brand' => 'Audi'],
    ['model' => 'W150', 'Brand' => 'Mercedes'],
    ['model' => 'W150', 'Brand' => 'Maruti'],
])

$cars->first();

// ['model' => 'A8', 'Brand' => 'Audi']

You can also use this method with an eloquent model to fetch the first record from the database:

$users = User::first(); //first User Model in the database.

only()

Laravel Collection’s only() method returns items from a collection with the specified keys.

$collection = collect(['name' => 'sapnesh', 'gender' => 'Male', 'age' => 24, 'Nationality' => US]);

$filtered = $collection->only(['gender', 'name']);

$filtered->all();

// ['gender' => 'Male', 'name' => 'sapnesh']

//Using the Illuminate\Support\Collection Class

$collection = new Collection(['name' => 'sapnesh', 'gender' => 'Male', 'age' => 24, 'Nationality' => US]);

$filtered = $collection->only(['gender', 'name']);

$filtered->all();

max()

max() method returns the element with the maximum value.

//Using Laravel Helper Method
$collection = collect([1, 1, 2, 3, 5, 8]);

$collection->max();

// 8

//Using the Class method

$collection = new Collection([1, 1, 2, 3, 5, 8]);

$collection->max();

// 8

Usage with Eloquent

Using max() with eloquent collections changes their behavior slightly. In Eloquent, you can use max() to fetch the model with the highest value of the specified key.

For Example,

$oldestUser = User::max('age');

The above example fetches the user from the database who has the oldest age.

search()

You can use the search() method to search a Collection for a given value and it returns a key (index) if the value is found.

There are three ways to use search()

  • Loose comparison: Loose comparison means that a string with an integer value will be successfully matched to an Integer with the same value.
$collection = collect([1, 1, 2, 3, 5, 8]);

$collection->search(3);

// 3

$collection->search(345);

//false

$collection->search("8"); // will match with the integer value in collection

//5
  • Strict Comparision: Unlike loose comparison, a strict comparison will make sure that the types of the provided input match with the type of values of the keys. To do this, you have to pass true as the second parameter to the search() method.
$collection = collect([1, 1, 2, 3, 5, 8]);

$collection->search(3);

// 3

$collection->search(345);

//false

$collection->search("8"); // will match with the integer value in collection

//5
  • Use custom search logic: You can also implement your own search logic with search(). You can implement it by passing a callback method:
$rolesCollection->search(function ($item, $key) {
    return $item == "Super Admin";
});

Sorting

Laravel Collections provide a number of methods for sorting a collection, let’s look at each in detail.

sort()

The sort() method sorts an array in ascending order.

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

$sorted = $collection->sort();

$sorted->values()->all();

// [1, 1, 4, 4, 5, 7]

sortDesc()

sortDesc() works similarly to the sort() method except that the sort is in descending order.

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

$sorted = $collection->sortDesc();

$sorted->values()->all();

// [7, 5, 4, 4, 1, 1]

sortBy()

Where the sort() method just sorts a collection, sortBy() can be used to sort a collection by a given key.

$collection = new Collection([
    ['age' => '25', 'gender' => 'Male'],
    ['age' => '18', 'gender' => 'Female'],
    ['age' => '74', 'gender' => 'Female'],
]);

$sorted = $collection->sortBy('gender');

$sorted->values()->all();

/*
    [
      ['age' => '18', 'gender' => 'Female'],
      ['age' => '74', 'gender' => 'Female'],
      ['age' => '25', 'gender' => 'Male'],
    ]
*/

pluck()

The pluck() method retrieves all the values of a given key from a collection. You can also use this method with Eloquent models as well.

$collection = collect([
      ['age' => '18', 'gender' => 'Female'],
      ['age' => '74', 'gender' => 'Female'],
      ['age' => '25', 'gender' => 'Male'],
]);

$plucked = $collection->pluck('age');

$plucked->all();

// [18, 74, 25]

With Eloquent, the usage is similar. You need to pass the column names as a parameter to extract their values. You can pass multiple arguments to the pluck() method specifying different columns.

//fetch all the emails in User Model (table)
$emails = User::all()->pluck('email', 'dob');

However, if your collection contains duplicate values, the plucked collection will only contain the last matching element.

zip()

You can use the zip() method to append values of an array to a given collection. Moreover, the original index is continued meaning that the first value of the array is going to be merged with the first value of the collection.

For example,

$collection = collect(['Cat', 'Dog']);

$zipped = $collection->zip([100, 200]);

$zipped->all();

// [['Cat', 100], ['Dog', 200]]

If the count of a given array is less than the number of elements in the collection, Laravel will add a null at the end of the remaining collection elements.

each()

This method lets you iterate over your collection items. each() accepts a callback function with two arguments, the current item in the loop and the key/index.

$userCollection->each(function ($item, $key) {
    info($item['email']);
});

In this above example, the code is simply logging the user’s email.

If you are trying to use each() with eloquent, you will be able to access all the properties of a model. Here is an example showing how to iterate over all the properties of a user model:

$users = App\User::all();
 
$users->each(function ($item, $key) {
    if($item->dob->isToday()) {
        $this->sendBirthdayWishes();
    }
});

Note: if you want to stop iterating at any point in the loop, just return false from the callback method.

Wrapping Up

These are some of the most useful Laravel collection methods that will make your life easier. There are more than 100 collection methods available and you can check them all here.

What’s your favorite Laravel collection method? Let us know in the comments below.