Map and Rename eloquent collection results in Laravel 5.5

Keyboard Slapper
2 min readMar 4, 2018

--

Note: There may be several other ways of doing this, this is just the way we do it :)

We recently made the decision to start using Laravel for all our new development and one of the questions we had was around renaming the eloquent results, we couldn’t find anything online to really show us how to do it so we thought we’d show you in case you needed to as well.

Why rename them though?

Its really just to hide the original names of your db columns. For example, if you open up Google Chrome, right click and click on inspect you’ll see something appear, if you look closely at the tabs you can select an option called Network.

When an ajax request is made, whether you’re sending something or receiving something, the request can be viewed in the network tab along with the results, so when results are returned they’ll normal be the column names that you have created in your database. We don’t want people to know the column names though, so we rename them.

How to do it?

// The array we're going to return
$data = [];
// Query the users table
$query = users::where('id', 1)->get();
// Let's Map the results from [$query]
$map = $query->map(function($items){
$data['user_firstName'] = $items->firstName;
$data['user_lastName] = $items->lastName;
return $data;
});
return $map;

It’s that simple!

Happy Mapping :)

--

--

Keyboard Slapper

Irish bloke | Coffee Addict | Contractor | Medium Newbie | Software Engineer | Technical Architect | Belfast | Boston | London