10 Awesome Laravel Collection Methods

In this tutorial, we will explain about 10 Awesome Laravel Collection Methods that you can use in your project.

10 Awesome Laravel Collection Methods

Laravel Eloquent uses Collections to return the results. Collections contains very useful methods that makes them very powerful and helpful to use. You can filter them, modify them and much more with them very conveniently. We will be looking at laravel collection methods in this tutorial.

Collections are not only limited to eloquent results but can be used separately. Eloquent results uses collections. You can simply create a collection by passing an array to collect helper function. All of the next collection methods listed below are applicable to both the eloquent collections and collections itself as well.

We know that Laravel is an awesome framework for web application development. One of the most awesome parts of this framework is Laravel Collection.

As Laravel Eloquent returns a collection when we grab a record from the database, it means  that we can use all collection methods on this model object. Laravel Collection is an enhance version of PHP arrays.

In this article, I will explain 10 Laravel Collection Methods. I recommend you to have a good grip on these methods and use them regularly.

Example Use Case

For the sake of this article, let’s assume we have product model and you have a query like this.

$products = Product::all();

In this section, $products variable is collection which contains the data in array format like below:

[
    [
        'name' => 'Gaming PC Dell Quad Core i5-2400',
        'price' => 349.95,
        'featured' => 1
    ],
    [
        'name' => 'Dell OptiPlex 7010 SFF 3rd Gen Quad Core',
        'price' => 181.95,
        'featured' => 0
    ],
    [
        'name' => 'HP 24fh Ultra-Slim IPS Monitor',
        'price' => 149.99,
        'featured' => 0
    ],
    [
        'name' => 'Microsoft Surface Pro 6 12.3-Inch Tablet',
        'price' => 679.99,
        'featured' => 1
    ],
    [
        'name' => 'Lenovo IdeaPad 320 15.6" HD Notebook',
        'price' => 299.99,
        'featured' => 0
    ],
]

1. Laravel Collection each()

The each() method iterate over the collection and pass the each item to a callback function with it’s $key which can be used as an index. For instance if we do interate through on our $products collection, we can do this way.

$products = Product::all();
$products->each(function ($item, $key) {
    return strtoupper($item['name']);
});
dd($products);

// Result will be like below //
Collection {#514 ▼
  #items: array:5 [▼
    0 => array:3 [▼
      "name" => "Gaming PC Dell Quad Core i5-2400"
      "price" => 349.95
      "featured" => 1
    ]
    1 => array:3 [▼
      "name" => "Dell OptiPlex 7010 SFF 3rd Gen Quad Core"
      "price" => 181.95
      "featured" => 0
    ]
    2 => array:3 [▼
      "name" => "HP 24fh Ultra-Slim IPS Monitor"
      "price" => 149.99
      "featured" => 0
    ]
    3 => array:3 [▼
      "name" => "Microsoft Surface Pro 6 12.3-Inch Tablet"
      "price" => 679.99
      "featured" => 1
    ]
    4 => array:3 [▼
      "name" => "Lenovo IdeaPad 320 15.6" HD Notebook"
      "price" => 299.99
      "featured" => 0
    ]
  ]
}

If you would like to stop the iteration you can simply return false like below:

$products = Product::all();
$products->each(function ($item, $key) {
    if (some condition here) {
        return false;
    }
});

2. Laravel Collection chunk()

If you split your collection into equal parts, then you can use chunk() method. This method will split the collection and make a smaller collection of given sizes.

$products = Product::all();
$chunk = $products->chunk(2);

dd($chunk->toArray());
// Result will be equal parts of arrays//
array:3 [▼
  0 => array:2 [▼
    0 => array:3 [▼
      "name" => "Gaming PC Dell Quad Core i5-2400"
      "price" => 349.95
      "featured" => 1
    ]
    1 => array:3 [▼
      "name" => "Dell OptiPlex 7010 SFF 3rd Gen Quad Core"
      "price" => 181.95
      "featured" => 0
    ]
  ]
  1 => array:2 [▼
    2 => array:3 [▼
      "name" => "HP 24fh Ultra-Slim IPS Monitor"
      "price" => 149.99
      "featured" => 0
    ]
    3 => array:3 [▼
      "name" => "Microsoft Surface Pro 6 12.3-Inch Tablet"
      "price" => 679.99
      "featured" => 1
    ]
  ]
  2 => array:1 [▼
    4 => array:3 [▼
      "name" => "Lenovo IdeaPad 320 15.6" HD Notebook"
      "price" => 299.99
      "featured" => 0
    ]
  ]
]

3. Laravel Collection every()

The every() method will check every element of the collection for a given condition. For example, for our above collection:

$every = $products->every(function ($item, $key){
    return $item['price'] > 100;
});

dd($every); // true

$every = $products->every(function ($item, $key){
    return $item['price'] > 300;
});

dd($every); // false

4. map()

This method will iterate on a collection and return value to a callback function which will form a new collection. In this callback function, you are free to modify the item and return it.

$products = Product::all();

$newPrices = $products->map(function ($item, $key) {
    return $item['price'] * 2;
});
dd($newPrices);
// Result will be
Collection {#510 ▼
  #items: array:5 [▼
    0 => 699.9
    1 => 363.9
    2 => 299.98
    3 => 1359.98
    4 => 599.98
  ]
}

5. Laravel Collection flip()

The flip() method swap the collection keys with their values.

$products = collect(['name' => 'iPhone', 'category' => 'phone']);

$flipped = $products->flip();

dd($flipped);
Collection {#509 ▼
  #items: array:2 [▼
    "iPhone" => "name"
    "phone" => "category"
  ]
}

The flip() method can do only flip the string and integer values as underneath it use the PHP’s native function array_flip().

6. Laravel Collection filter()

The filter() method will filter the collection with a given callback function and keep items in the collection which pass the callback test.

$products = Product::all();

$filtered = $products->filter(function ($item, $key) {
    return $item['price'] > 300;
});
dd($filtered);
Collection {#510 ▼
  #items: array:2 [▼
    0 => array:3 [▼
      "name" => "Gaming PC Dell Quad Core i5-2400"
      "price" => 349.95
      "featured" => 1
    ]
    3 => array:3 [▼
      "name" => "Microsoft Surface Pro 6 12.3-Inch Tablet"
      "price" => 679.99
      "featured" => 1
    ]
  ]
}

7. Laravel Collection forget()

The forget() method will remove an item from the collection by a given key.

$products = collect(['name' => 'iPhone', 'category' => 'phone']);

$products = $products->forget('category');

dd($products);
Collection {#514 ▼
  #items: array:1 [▼
    "name" => "iPhone"
  ]
}

8. Laravel Collection keyBy()

The keyBy() method keys the colllection with the given key.

$products = Product::all();
$keyed = $products->keyBy('price');

dd($keyed);
Collection {#510 ▼
  #items: array:5 [▼
    349 => array:3 [▼
      "name" => "Gaming PC Dell Quad Core i5-2400"
      "price" => 349.95
      "featured" => 1
    ]
    181 => array:3 [▼
      "name" => "Dell OptiPlex 7010 SFF 3rd Gen Quad Core"
      "price" => 181.95
      "featured" => 0
    ]
    149 => array:3 [▼
      "name" => "HP 24fh Ultra-Slim IPS Monitor"
      "price" => 149.99
      "featured" => 0
    ]
    679 => array:3 [▼
      "name" => "Microsoft Surface Pro 6 12.3-Inch Tablet"
      "price" => 679.99
      "featured" => 1
    ]
    299 => array:3 [▼
      "name" => "Lenovo IdeaPad 320 15.6" HD Notebook"
      "price" => 299.99
      "featured" => 0
    ]
  ]
}

You can also pass a callback function to keyBy() method which will work like below:

$products = Product::all();
$keyed = $products->keyBy(function ($item) {
    return $item['featured'];
});
dd($keyed);
Collection {#510 ▼
  #items: array:2 [▼
    1 => array:3 [▼
      "name" => "Microsoft Surface Pro 6 12.3-Inch Tablet"
      "price" => 679.99
      "featured" => 1
    ]
    0 => array:3 [▼
      "name" => "Lenovo IdeaPad 320 15.6" HD Notebook"
      "price" => 299.99
      "featured" => 0
    ]
  ]
}

Note that if multiple items have the same key then the last one will be returned.

9. Laravel Collection pluck()

The pluck() method will return the values of a given key.

$products = Product::all();
$pluckedProducts = $products->pluck('name');

dd($pluckedProducts->all());
array:5 [▼
  0 => "Gaming PC Dell Quad Core i5-2400"
  1 => "Dell OptiPlex 7010 SFF 3rd Gen Quad Core"
  2 => "HP 24fh Ultra-Slim IPS Monitor"
  3 => "Microsoft Surface Pro 6 12.3-Inch Tablet"
  4 => "Lenovo IdeaPad 320 15.6" HD Notebook"
]

10. Laravel Collection isEmpty() and isNotEmpty()

The isEmpty() method will return true if the given collection is empty, otherwise it will return false.

$products = Product::all();
$products->isEmpty(); // false  //

The isNotEmpty() method will return true if the given collection is not empty, otherwise it will return false.

$products = Product::all();
$products->isNotEmpty(); // true //

It seems that when you’re using Laravel, certain things keep coming up over and over again. The first thing is certainly the architecture the framework uses, service providers, and understanding how the inversion of control container works.

There are a few core things we all try to have under our belt. It seemed like collections were next up as far as something that it would be worth having a really solid grasp of.

What better way to learn it than to complete the mega laravel collections tutorial!? In addition, it’s always really enlightening to look under the hood at the source to see how the magic happens. Having an understanding of the tool or framework you use gives confidence.

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *