In this tutorial, we will explain about 10 Awesome Laravel Collection Methods that you can use in your project.
Laravel Eloquent uses Collections to return the results. Collections contains very useful methods that makes them very powerful and helpful to use. You can filter them, modify them and much more with them very conveniently. We will be looking at laravel collection methods in this tutorial.
Collections are not only limited to eloquent results but can be used separately. Eloquent results uses collections. You can simply create a collection by passing an array to collect helper function. All of the next collection methods listed below are applicable to both the eloquent collections and collections itself as well.
We know that Laravel is an awesome framework for web application development. One of the most awesome parts of this framework is Laravel Collection.
As Laravel Eloquent returns a collection when we grab a record from the database, it means that we can use all collection methods on this model object. Laravel Collection is an enhance version of PHP arrays.
In this article, I will explain 10 Laravel Collection Methods. I recommend you to have a good grip on these methods and use them regularly.
Example Use Case
For the sake of this article, let’s assume we have product model and you have a query like this.
$products = Product::all();
In this section, $products variable is collection which contains the data in array format like below:
The each() method iterate over the collection and pass the each item to a callback function with it’s $key which can be used as an index. For instance if we do interate through on our $products collection, we can do this way.
It seems that when you’re using Laravel, certain things keep coming up over and over again. The first thing is certainly the architecture the framework uses, service providers, and understanding how the inversion of control container works.
There are a few core things we all try to have under our belt. It seemed like collections were next up as far as something that it would be worth having a really solid grasp of.
What better way to learn it than to complete the mega laravel collections tutorial!? In addition, it’s always really enlightening to look under the hood at the source to see how the magic happens. Having an understanding of the tool or framework you use gives confidence.