Laravel collection map method example

 

In this post, I will explain the Laravel collection map method with an example. I will simply demonstrate how to use the Laravel eloquent collection map method. We will focus on how to use the Laravel collection map efficiently.

The map() method in Laravel is a collection method that allows you to apply a callback function to each item in a collection. It is a powerful method for manipulating data in Laravel collections. The map() method returns a new collection object with updated items.

I will provide you with simple examples of using the map() method in Laravel collections. Let’s see an example below that will help you understand its usage.

Laravel collection map() method example
Syntax:
$collection->map(
callback
);
Example 1: Laravel collection map() example
  public function index()
    {
       $collection = collect(['first', 'second', 'three', 'fourth', 'fifth']);

       $modifyData = $collection->map(function ($data, $key) {
            return strtoupper($data);
       });

       dd($modifyData);
    }
Output:
  #items: array:5 [▼
    0 => "FIRST"
    1 => "SECOND"
    2 => "THREE"
    3 => "FOURTH"
    4 => "FIFTH"
  ]
Example 2: Laravel Eloquent collection map

If you need to add a new column name to your API response or frontend side, you can easily use the map() method to achieve that, as shown in the example below.

 public function index()
    {
        $collection = User::get();

        $modifyData = $collection->map(function ($data, $item) {
            return  [
                'id' => $data->id,
                'name' => $data->name,
                'status' => $data->email_verified !== null ? 1 : 0
            ];
        });

       dd($modifyData);
    }

I hope this tutorial help you.

Leave a Reply

Your email address will not be published. Required fields are marked *