DEV Community

Peter Fox
Peter Fox

Posted on • Originally published at Medium on

Laravel Internals: Complex Array building

Photo by Ben Allan on Unsplash

One of the most common issues you can have in PHP is merging arrays and the complications of having to selectively include or exclude particular keys when needed. Laravel actually has a built in trait for this that’s great to use for these situations.

If you use Laravel’s HTTP resources you’ll be familiar with this developer experience. Under the hood resources in Laravel rely on the ConditionallyLoadAttributes trait.

To keep things clear in the example I’ve created two models, Person and Address, with Address being a hasOne relation for the Person. The example class is simply called TransformObjectToArray which has a method called transform which accepts a Person and an additional array of attributes.

This is workable but it often becomes complicated and harder to read.

And here’s how we could do this if we used the ConditionallyLoadAttributes trait instead.

As you can see in the example we have everything neatly occuring in a return statement that shows us what the structure of the array will look like somewhat.

If you’re struggling to understand the functionality of the when and merge methods used in the example you can read about them in the Laravel docs as part of the resources documentation. The filter method is purely there to perform the action of handling the operations to remove keys or merge arrays. All of these methods are provided via the trait.

The ConditionallyLoadAttributes trait is something truly worth using in your own classes when developing with Laravel when working with building complex arrays outside of the typical API Responses.

I’m Peter Fox, a software developer in the UK who works with Laravel among other things. Thank you for reading my article, I’ve got several more on both medium and If you want to know more about me, head over to Also feel free to follow me @SlyFireFox on twitter for more Laravel tips and tutorials in the future.

Top comments (0)