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 first place you'll want to apply collection support is anywhere you're using eager loading. The result will be one block of code that you can use for both eager-loaded and lazy-loaded elements, reducing errors in your code, as well as code duplication.
The first place you’ll want to apply collection support is anywhere you’re using eager loading. The result will be one block of code that you can use for both eager-loaded and lazy-loaded elements, reducing errors in your code, as well as code duplication.
Since version 2.6, Craft returns eager-loaded elements as arrays, and we have to iterate over them as a standard array.
When eager loading an asset element, you’re probably familiar with having to access the image itself via the index (entry.asset[0]
) instead of via .one()
since that .one()
method isn’t available on a standard array.
You have to update your Twig code if you decide to eager load an element and it makes some code not reusable because if a query isn’t eager-loading the element, you can’t access it as an array via the index.
So, how does the addition of Laravel Collections help with eager loading?
The code is more straightforward and reusable.
Craft 4 returns all eager-loaded elements as collections instead of standard data arrays. Because of this change, we don’t need to have a special case using an array index to access the element.
What's New in Craft CMS 4 is made up of the following videos: