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

Collections and Eager-Loading

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 col­lec­tion sup­port is any­where you’re using eager load­ing. The result will be one block of code that you can use for both eager-loaded and lazy-loaded ele­ments, reduc­ing errors in your code, as well as code duplication.

Since ver­sion 2.6, Craft returns eager-loaded ele­ments as arrays, and we have to iter­ate over them as a stan­dard array. 

When eager load­ing an asset ele­ment, you’re prob­a­bly famil­iar with hav­ing to access the image itself via the index (entry.asset[0]) instead of via .one() since that .one() method isn’t avail­able on a stan­dard array.

You have to update your Twig code if you decide to eager load an ele­ment and it makes some code not reusable because if a query isn’t eager-load­ing the ele­ment, you can’t access it as an array via the index. 

So, how does the addi­tion of Lar­avel Col­lec­tions help with eager loading?

The code is more straight­for­ward and reusable.

Craft 4 returns all eager-loaded ele­ments as col­lec­tions instead of stan­dard data arrays. Because of this change, we don’t need to have a spe­cial case using an array index to access the element.