Use Collections to Enhance Results in laravel 5.1

Until now, I told you everything about models and how to create relationships between them. I explained you how to query your data and relationships and even to specify complex conditions and constraints. However, I have never told you anything about what Eloquent’s outputs are. Yes, sometimes, I mentioned an array or just the word results. Don’t worry; it wasn’t wrong, but there is something more under the hood.

Well, in this article, I will discuss collections. When retrieving your results from a query (using, for instance, get() or all()), you are getting a collection. That’s the right term to use.

Basically, you can think of a collection as an array of results but with some extra utility methods. In fact, when you use a collection, you are using an instance of the Collection class under IlluminateDatabaseEloquent.

This class implements the AggregateIterator interface that lets you treat a collection like an array. You can use collections to perform many operations, sometimes complex operations as well. First of all, you will see how to perform some basic research operations and checks with collections.

Then, we will see some results transformation methods. Straight after, we will go a little deeper; after all, a collection is made up of elements. We will work with these elements. With a collection, obviously, you can iterate through its elements. There are some dedicated methods for iterations. Also, you will learn how to filter a collection in an easy way, just as many things in Eloquent are easy. Finally, we will talk about sorting operations on collections and how to deal with them. So, nothing of this really is essential, but it will help you to better understand how Eloquent works in every single way.

Are you ready? Here are the topics to cover:

  • Basic collection operations
  • Transforming collections
  • Iterating and filtering
  • Sorting

 

About the author

Deven Rathore

I'm Deven Rathore, a multidisciplinary & self-taught designer with 3 years of experience. I'm passionate about technology, music, coffee, traveling and everything visually stimulating. Constantly learning and experiencing new things.

Pin It on Pinterest