Should this be a collection or an array?

Use the right tool for the job

Joel Clermont
Joel Clermont

Code review is an opportunity to learn from others and get better at what you do. Even a simple question can make you take a step back and think about why you did something a certain way.

Recently, Aaron was reviewing my code where I added a method to a model that was filtering, mapping, and sorting a JSON property, and then I cast the result to an array before returning it. My method was then being used in a Blade template to create a comma-separated list of values with the PHP implode() function.

Aaron asked: Why are you casting this to an array? Why not just leave it as a collection, and then use the built-in $collection->implode() method instead?

It was a tiny thing, but it was a good point. Why was I doing this extra cast, when the collection would work just as well? So I simplified the code, left it as a collection, and was grateful for the feedback.

The point of bringing this up isn't to make a rule one way or the other, but to remind you to think about the context for a given piece of code. At a minimum, you should have a reason why you're choosing to cast an array to a collection, or the other way around.

Here to help,


P.S. Don't have anyone to review your code? You can always share a small snippet of code in our private Laravel community to get friendly feedback.

Toss a coin in the jar if you found this helpful.
Want a tip like this in your inbox every weekday? Sign up below 👇🏼

Level up your Laravel skills!

Each 2-minute email has real-world advice you can use.