12 Laravel Collection Methods You Should Be Using Everyday

12 Laravel Collection Methods You Should Be Using Everyday

We all 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, which means we can use all collection methods on this model object. Laravel Collection is just an enhanced version of PHP arrays.

In this post, I will share 12 Laravel Collection Methods, which I use on a daily basis to make my job easier. I recommend you to have a good grip on these methods and use them regularly.

Example Use Case

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

$products = Product::all();

In this case, $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 example if we want to 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 want to 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()

The map() method is one of my favorite one. 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. Like below:

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

$flipped = $products->flip();

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

The flip() method can 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"
]

You can read our post Using Laravel Pluck To Extract Certain Values to have a better understanding.

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

11. Laravel Collection sortBy()

The sortBy() method will sort a collection by a given key. This method keeps the original keys, so we can use values() method to reset the keys.

$products = Product::all();
$sorted = $products->sortBy('featured');
$sorted->values()->all();
// Result will be
Collection {#510 ▼
  #items: array:5 [▼
    2 => array:3 [▼
      "name" => "HP 24fh Ultra-Slim IPS Monitor"
      "price" => 149.99
      "featured" => 0
    ]
    1 => array:3 [▼
      "name" => "Dell OptiPlex 7010 SFF 3rd Gen Quad Core"
      "price" => 181.95
      "featured" => 0
    ]
    4 => array:3 [▼
      "name" => "Lenovo IdeaPad 320 15.6" HD Notebook"
      "price" => 299.99
      "featured" => 0
    ]
    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
    ]
  ]
}

You can also pass a callback function to apply a condition to each item and then sort it.

12. Laravel Collection reject()

The reject() methos also filter the collection using a given callback function. The callback function should return true if you want to remove a particular item from the collection.

$products = Product::all();
$filtered = $products->reject(function ($value, $key) {
    return $value['price'] > 300;
});

dd($filtered);
Collection {#516 ▼
  #items: array:3 [▼
    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
    ]
    4 => array:3 [▼
      "name" => "Lenovo IdeaPad 320 15.6" HD Notebook"
      "price" => 299.99
      "featured" => 0
    ]
  ]
}

That’s all for now from me. Which collection function you like most, let me know in the comments box below.

2 comments on “12 Laravel Collection Methods You Should Be Using Everyday

  1. The first example is wrong. Perhaps you refer to something like the following?

    $products->each(function($item, $key) { $item->name = strtoupper($item->name); });

Leave a Reply

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

*When sharing a code snippet please wrap you code with pre tag and add a class code-block to it like below.
<pre class="code-block">you code here</pre>

*
*

This site uses Akismet to reduce spam. Learn how your comment data is processed.