<p>Apologies, I misread the question the first time around.</p>

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

<p>See: <a href="https://docs.craftcms.com/v3/dev/eager-loading-elements.html#eager-loading-elements-related-to-matrix-blocks" rel="nofollow noreferrer">https://docs.craftcms.com/v3/dev/eager-loading-elements.html#eager-loading-elements-related-to-matrix-blocks</a> for more details</p>

CC BY-SA 4.0
2019-10-31T11:42:45.717Z
2019-10-31T11:42:45.717Z
Nick
<p>You need to loop through the array returned by your element query</p>

<pre><code>foreach ($relatedOffers as $offer) {
    print_r($offer-&gt;category);
}
</code></pre>

CC BY-SA 4.0
2019-10-01T12:28:43.387Z
The array is empty, so there's nothing to loop through.
jpea
CC BY-SA 4.0
2019-10-01T09:10:35.070Z
2019-10-01T09:10:35.070Z
Nick
<p>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:</p>

<p>locationOffers is a matrix block name, category is the handle of a related category field inside of the matrix block</p>

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

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

<plugin-development><eager-loading>
Eager loading category data from a Matrix block
# Eager loading category data from a Matrix block

(Asked by: username_0 on 2019-09-30)

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();

**Tags:** plugin-development, eager-loading


---

## 2 answers

### Answer by username_1 on 2019-10-31. Score: 3 | Accepted answer

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


---

### Answer by username_1 on 2019-10-01. Score: 1

You need to loop through the array returned by your element query
foreach ($relatedOffers as $offer) {
    print_r($offer->category);
}

> **Comments:**
> **username_0**: The array is empty, so there's nothing to loop through.  

---

