8

Laravel Collection map Method Example

 1 year ago
source link: https://www.laravelcode.com/post/laravel-collection-map-method-example
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Laravel Collection map Method Example

  1385 views

  11 months ago

Laravel

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.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK