Laravel collection map method

Hello guys,

Laravel collection provides reach methods to work with array. It provides additional support to the Elequent query object which you have already collected.

In this article, we will discuss on map() method, one of the useful collection method. map method iterate all items in the collection and return it given callback. In the callback, we can modify all items in the collection and create new collection.

For example, if we want to implement ucfirst method on all of the items in array, then we can do it like below: 


public function index()
    $fruits = collect(["apple", "mango", "orange", "banana", "pineapple"]);
    $uc_fruits = $fruits->map(function($item, $key) {
       return ucfirst($item);

    // ["Apple", "Mango", "Orange", "Banana", "Pineapple"]

In other example, if we want to check if given items in array is divisible by 5 or not. This way, you can use conditional operator to every items in array.


$numbers = collect([5, 10, 15, 20, 22, 50]);
$divisible_by_5 = $numbers->map(function($item, $key) {
   return ($item%5 == 0 );
// [true, true, true, false, true]

This way you can work with collection using map() method.