map function in laravel

    By: Manu
    2 years ago

    Laravel Collection map() Example


    Here is the easiest example of laravel collection map example. I explained simply about laravel eloquent collection map. So we use laravel collection map. This guide goes in detailed to demonstrate laravel map function usage.

    The map method gives callback function to each element of a collection. The callback function can modify an element in collection and we can create a new collection.

    So you can laravel map function in laravel 5, laravel 6, laravel 7 and laravel 8 application. Let's see bellow example.


    $collecton->map(
    
        Callback     // here we can add our logic 
    
    );
    

    Here is another code example

    public function showData()
    
    {
    
        $collection = collect(["john", "mark", "martin", "roger", "manu"]);  // Here we convert array to collection
    
      
        // Bellow we are mapping through collection elements.
    
        $modified = $collection->map(function($item, $key) {
            
             return strtoupper($item);  // Here we changing each name to uppercase which then goes in $modified variable
    
        });
    
        dd($modified);
    
    }
    

    Here is the output

    Illuminate\Support\Collection Object
    
    (
    
        [items:protected] => Array
    
            (
    
                [0] => JOHN
    
                [1] => MARK
    
                [2] => MARTIN
    
                [3] => ROGER
    
                [4] => MANU
    
            )
    
    )