The Convenience of Collections in Craft CMS 4

Some examples of using Laravel Collections methods instead of Twig filters in Craft CMS 4.

Image

The improve­ments with eager-load­ing ele­ments are the pri­ma­ry advan­tage of col­lec­tions. But we can use the collect() method any­where to con­vert data to a col­lec­tion and then manip­u­late it with the Lar­avel Col­lec­tions methods.

We’ll take this stan­dard ele­ment query, and, instead of call­ing the .all() method to exe­cute the query and return results, we’ll call .collect(), which will also exe­cute a query but return the results as a Lar­avel Col­lec­tions array.

{% set entries = craft.entries()
    .section('blog')
    .limit(25)
    .collect() 
%}

This opens up to us all of the meth­ods avail­able to a Col­lec­tions array. The best place to refer to for these meth­ods is the Lar­avel documentation.

Let’s group entries based on the sec­tion han­dle. Typ­i­cal­ly, I’d use the group fil­ter fil­ter in Twig:

{% set entries = craft.entries()  
 .section(['blog', 'podcast', 'review'])  
 .limit(25)  
 .all() %}  
 
{% set groupBySection = entries | group('section.handle') %}  

But since we already have a col­lec­tion, we can use the col­lec­tion groupBy() method:

{% set entries = craft.entries()  
 .section(['blog', 'podcast', 'review'])  
 .limit(25)  
 .collect() %}
 
{% set groupBySection = entries.groupBy('section.handle') %}  

Sim­i­lar­ly, we can replace the batch fil­ter with the chunk() method. Here’s the batch filter:

{% set entries = craft.entries()  
 .section(['blog', 'podcast', 'review'])  
 .limit(25)  
 .all() %}  
 
{% set setOfThree = entries | batch(3) %}  

And the same results but using a col­lec­tion and the chunk() method:

{% set entries = craft.entries()  
 .section(['blog', 'podcast', 'review'])  
 .limit(25)  
 .collect() %}  
 
{% set setOfThree = entries.chunk(3) %}

And, these are just two exam­ples of using col­lec­tions meth­ods in Twig. There are dozens of meth­ods to choose from!