Create a free account to get access to additional free training videos. Enjoy this free video from CraftQuest! Create a free account to get access to additional free training videos. Join the Community

What's New in Craft CMS 4

Collection Methods

The improvements with eager-loading elements are the primary advantage of collections. But we can use the collect() method anywhere to convert data to a collection and then manipulate it with the Laravel Collections methods.

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. 

If we dump out the results of that query, you can see the different:

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

{% dd(entries) %}

Addi­tion­al­ly, since we are using Col­lec­tions, we can take advan­tage of the dd method that comes with the collection:

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

{{ entries.dd }}

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') %}  
 
 {% dd(groupBySection) %}


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') %}  

  {{ groupBySection.dd }}

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) %}  
 
 {% dd(setOfThree) %}

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) %}  
 
 {{ setOfThree.dd }}

What's New in Craft CMS 4 is made up of the following videos: