How to use Laravel Transform
Posted on:December 13, 2018 at 10:00 AM
You will get an example in Laravel documentation that shows how to use transform()
in Laravel. You might see example code like this:
$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’s not clear to you and you need a more in-depth real-life example, then let’s see another example.
Imagine that you have a users
collection that contains:
- id
- name
- created_at
- updated_at
Now, during returning this data, you want to inject one or more records with each. For example, you want to inject a location
column with each iteration.
The code will be like this:
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.