DEV Community

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

Posted on

1 1

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?

Image of Datadog

The Future of AI, LLMs, and Observability on Google Cloud

Datadog sat down with Google’s Director of AI to discuss the current and future states of AI, ML, and LLMs on Google Cloud. Discover 7 key insights for technical leaders, covering everything from upskilling teams to observability best practices

Learn More

Top comments (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...)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay