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
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 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.
We’ll take this standard element query, and, instead of calling the .all()
method to execute the query and return results, we’ll call .collect()
, which will also execute a query but return the results as a Laravel Collections array.
{% set entries = craft.entries()
.section('blog')
.limit(25)
.collect()
%}
This opens up to us all of the methods available to a Collections array. The best place to refer to for these methods is the Laravel 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) %}
Additionally, since we are using Collections, we can take advantage 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 section handle. Typically, I’d use the group
filter filter 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 collection, we can use the collection groupBy()
method:
{% set entries = craft.entries()
.section(['blog', 'podcast', 'review'])
.limit(25)
.collect() %}
{% set groupBySection = entries.groupBy('section.handle') %}
{{ groupBySection.dd }}
Similarly, we can replace the batch
filter 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 collection and the chunk()
method:
{% set entries = craft.entries()
.section(['blog', 'podcast', 'review'])
.limit(25)
.collect() %}
{% set setOfThree = entries.chunk(3) %}
{{ setOfThree.dd }}