How to use Laravel Transform

Laravel 13 Dec 2018

You will get an example in Laravel documentation that how to use transform() in Laravel. You might see example code like that-

$collection = collect([1, 2, 3, 4, 5]);

$collection->transform(function ($item, $key) {
    return $item * 2;
});

$collection->all();

// [2, 4, 6, 8, 10]

Easy enough, right?

However, if it is not clear to you, and you need a more in-depth real-life example, then let's see another example.

Imagine that, I have a users collection that contains

  • id
  • name
  • email
  • created_at
  • updated_at

Now, during returning this data, you want to inject one or more record with each. For example, I want to inject a location column with each iteration.

The code will be like that-

public function index()
{
        $users = User::latest()->get();

        /*
        // sample output
        {
            "id": 1,
            "name": "John Doe",
            "email": "[email protected]",
            "created_at": "2018-12-13 19:34:44"
            "updated_at": "2018-12-13 19:34:44"
        },
        {...}
        */

        $users->transform(function($transform){
            $transform->location = "Kuala Lumpur";

            return $transform;
        });

        /*
            // transformed output
            {
                "id": 1,
                "name": "John Doe",
                "email": "[email protected]",
                "location": "Kuala Lumpur",
                "created_at": "2018-12-13 19:34:44"
                "updated_at": "2018-12-13 19:34:44"
            },
            {...}
        */
}

Hope, it makes a clearer image to you.

Thank you.