In this episode, we're diving into a really handy new feature for Laravel developers: the collectedBy
attribute. If you've worked with custom collections in your Laravel apps, this is going to make your life a lot easier! Even if you haven't created custom collections before, we'll walk through the process together.
First, we start off by generating some sample data with a user factory so we have some users in the database to play with. Then, I show how Eloquent returns your database results as a standard collection class, which gives you all those convenient collection methods to work with your data.
Next up, I explain why you might want a custom collection—maybe to add extra methods or special behavior to the group of models you pull from the database. We create a new UserCollection
class to demonstrate this, extending the base collection class. Traditionally, to tell Laravel to use your custom collection, you'd override the newCollection
method in your model.
But here's the exciting part: with Laravel's new collectedBy
attribute, you don't have to go through the hassle of overriding methods. Instead, you just add one attribute at the top of your model specifying your custom collection class, and Laravel takes care of the rest.
So in short: custom collections are now way simpler to use—just set the collectedBy
attribute on your model and you're good to go! Less boilerplate, more convenience.