How might I eager load category data in a plugin? I can't seem to figure out why I can't access a category in this way:

locationOffers is a matrix block name, category is the handle of a related category field inside of the matrix block

// this adds an empty category array to each related offer
$relatedOffers = $entry->locationOffers->with(['category'])->all(); 
print_R($relatedOffers->category); // is empty

// this regular way works, where I can access category->title, and more, 
// but is not eager loaded
$relatedOffers = $entry->locationOffers->all();

2 Answers 2


Apologies, I misread the question the first time around.

When eager loading via a matrix block, you need to provide a blocktype as well as the field name.

See: https://docs.craftcms.com/v3/dev/eager-loading-elements.html#eager-loading-elements-related-to-matrix-blocks for more details


You need to loop through the array returned by your element query

foreach ($relatedOffers as $offer) {
  • The array is empty, so there's nothing to loop through.
    – jpea
    Oct 1, 2019 at 12:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.