DEV Community

Cover image for Supercharge your Laravel 8 Collections
Zack Webster
Zack Webster

Posted on

Supercharge your Laravel 8 Collections

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
  • at
    • second
    • third
    • fourth
    • fifth
    • sixth
    • seventh
    • eighth
    • ninth
    • tenth
  • before
  • catch
  • chunkBy
  • collectBy
  • eachCons
  • extract
  • filterMap
  • firstOrFail
  • fromPairs
  • glob
  • groupByModel
  • head
  • ifAny
  • ifEmpty
  • none
  • paginate
  • parallelMap
  • pluckToArray
  • prioritize
  • rotate
  • sectionBy
  • simplePaginate
  • sliceBefore
  • tail
  • try
  • toPairs
  • transpose
  • validate
  • withSize

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?

Discussion (1)

Collapse
bdelespierre profile image
Benjamin Delespierre

That's such a great idea.

Also I think it's worth noting that EloquentCollection can be specialized on a model basis like this:

class User extends Model
{
    public function newCollection(array $models = [])
    {
        return new UserCollection($models);
    }
}

class UserCollection extends Illuminate\Database\Eloquent\Collection
{
    public function admins(): self
    {
        return $this->filter($user => $user->isAdmin());
    }
}
Enter fullscreen mode Exit fullscreen mode

So you can do

User::all()->admins();
Enter fullscreen mode Exit fullscreen mode

(this example is purposefully oversimplified and in that specific case, one would better use scope...)