Element API: Get Matrix Content So I'm trying to get my Matrix as JSON with the Craft CMS Element API plugin.

&lt;?php

use Craft\elements\Entry;

return [
    'endpoints' =&gt; [
        'api/sites' =&gt; [
            'elementType' =&gt; craft\elements\Entry::class,
            'criteria' =&gt; ['section' =&gt; 'sites'],
            'elementsPerPage' =&gt; 1,
            'transformer' =&gt; function(Entry $entry) {
                $matrixBlocks =[];
                foreach ($entry-&gt;contentMatrix as $block) {
                    switch ($block-&gt;type-&gt;handle) {
                        case 'sectionTitleBlock':
                            $matrixBlocks[] = [
                                'content' =&gt; $block-&gt;sectionTitleBlock
                            ];
                            break;
                    }
                }
                return [
                    'matrix' =&gt; $matrixBlocks,
                ];
            },
            'paginate' =&gt; false,
            'pretty' =&gt; true,
        ],
    ]
];


The error message im getting is 


  "error": {
      "code": 2,
      "message": "Invalid argument supplied for foreach()"
    }


I think the problem is that $entry-&gt;contentMatrix is giving me a MatrixBlockQuery Element.

$sectionTitleBlock is a normal text field
In order to get all related items from a BaseRelationField you'll need this syntax

$entry-&gt;getFieldValue('contentMatrix')-&gt;all() 


Thus your loop will be

foreach($entry-&gt;getFieldValue('contentMatrix')-&gt;all() as $block){