Table of contents

Laravel Collection Map

Do you want to learn the Laravel collection map() with an example, In this post, I will explain how to implement the Laravel collection map method in your project. The Laravel map method loop through the collection and pass each value to the given callback.


We can able to modify the item of the callback and create a new Laravel collection before returning it.

 

I will give you several examples so that it is easy to understand and apply to your Laravel project.

 

Syntax:

$collecton->map(
    Callback
);

 

Laravel Collection map() Example #1

In this example, we can able to check and return only the even numbers with the Laravel collection map() method.

$collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
 
$modified = $collection->map(function ($item, $key) {
    // return only even numbers
    if($item % 2 == 0) {
        return $item;
    }
});

dd($modified->all());

//result

Array
(
    [0] => 
    [1] => 2
    [2] => 
    [3] => 4
    [4] => 
    [5] => 6
    [6] => 
    [7] => 8
    [8] => 
    [9] => 10
)

 

 

Laravel Collection map() Example #2

The below example will get all users and only display the status with the Active value. But take note this is an example only you can also apply a query like ->where('status', 'Active'). I just show it to you how to use the Laravel collection map to modify the items. I also added ucwords function to ensure that the first_name and last_name values uppercase the first letter. So we have unlimited ways to modify the map() callback method.

$users = User::all();
 
$users = $users->map(function ($item, $key) {
    if($item->status == 'Active') {
        return [
            'first_name' => ucwords($item->first_name),
            'last_name' => ucwords($item->last_name),
            'email' => $item->email
        ];
    }
});
 
print_r($users->all());

//result
Array
(
    [0] => Array
        (
            [first_name] => Ark
            [last_name] => Admin
            [email] => admin@domain.com
        )

    [1] => Array
        (
            [first_name] => Ark
            [last_name] => User
            [email] => user@domain.com
        )

    [2] => Array
        (
            [first_name] => Kirsten
            [last_name] => Larkin
            [email] => hyatt.bernadine@example.org
        )

    [3] => Array
        (
            [first_name] => Silas
            [last_name] => Thiel
            [email] => towne.branson@example.com
        )

    [4] => Array
        (
            [first_name] => Layne
            [last_name] => Wilkinson
            [email] => abruen@example.org
        )

    [5] => Array
        (
            [first_name] => Marley
            [last_name] => Weissnat
            [email] => iterry@example.org
        )

)

 

That's pretty much it. I hope it helps thank you for reading :)