Laravel is amazing when it comes to what it offers right out of the box. It makes our lives as developers just that much easier. Collections are a big part of Laravel. They come with a ton of methods. But sometimes you need a little extra.
I recently came across an amazing package: spatie/laravel-collection-macros.
Getting up and running with it couldn't be any simpler. All it takes is one composer command:
composer require spatie/laravel-collection-macros
and the package will automatically register itself!
The package macros in the following methods:
after-
atsecondthirdfourthfifthsixthseventheighthninthtenth
beforecatchchunkBycollectByeachConsextractfilterMapfirstOrFailfromPairsglobgroupByModelheadifAnyifEmptynonepaginateparallelMappluckToArrayprioritizerotatesectionBysimplePaginatesliceBeforetailtrytoPairstransposevalidatewithSize
I wouldn't be surprised if some of these make their way into upcoming Laravel versions. Having recently used paginate() & simplePaginate() on collections, all I can say is this works like a charm.
That's All Folks!
Thanks for reading my article.
Feel free to discuss in the comments below.
☕ Buy me a Coffee?
Top comments (1)
That's such a great idea.
Also I think it's worth noting that EloquentCollection can be specialized on a model basis like this:
So you can do
(this example is purposefully oversimplified and in that specific case, one would better use scope...)