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: 

<?php

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

    dd($uc_fruits);
    // ["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.

<?php

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

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

Was this article helpful?

0 out of 0 person found this article helpful.

Leave a comment

Or

No Comment