Matrix block Element API call on null error I get this JSON error when trying to output content of a matrix block called proLinks using the Element API.


  Call to a member function all() on null


The code is as follows (I've shortened it and removed the other content, this is the only one that I can't get to work):

&lt;?php

use craft\elements\Entry;

return [
  'endpoints' =&gt; [
    'discproj.json' =&gt; function() {
      return [
        'elementType' =&gt; Entry::class,
        'criteria' =&gt; ['section' =&gt; 'dPs'],
        'transformer' =&gt; function(Entry $entry) {

          $linkBlocks = [];
          foreach ($entry-&gt;proLinks-&gt;all() as $block) {
            switch ($block-&gt;type-&gt;handle) {
              case 'external':
              $linkBlocks[] = [
                'externalTitle' =&gt; $block-&gt;externalTitle,
                'externalLink' =&gt; $block-&gt;externalLink,
              ];
              break;
            }
          }

          return [
            'projectLinks' =&gt; $linkBlocks,
          ];
        },
      ];
    },
  ]
];


I've looked at the other questions about this here, and they all seem to do things a little bit different from each other. I think I have the general structure, but there is obviously something missing.
I figured it out. Not every entry uses the matrix block, the error appears when the script hits that empty/non-existing block (null) it can't go looking for something inside it. Adding a conditional around the foreach solves it.

&lt;?php

use craft\elements\Entry;

return [
  'endpoints' =&gt; [
    'discproj.json' =&gt; function() {
      return [
        'elementType' =&gt; Entry::class,
        'criteria' =&gt; ['section' =&gt; 'dPs'],
        'transformer' =&gt; function(Entry $entry) {

          $linkBlocks = null;
          if ($entry-&gt;proLinks) {
            foreach ($entry-&gt;proLinks-&gt;all() as $block) {
              switch ($block-&gt;type-&gt;handle) {
                case 'external':
                $linkBlocks[] = [
                  'externalTitle' =&gt; $block-&gt;externalTitle,
                  'externalLink' =&gt; $block-&gt;externalLink,
                ];
                break;
              }
            }
          }

          return [
            'projectLinks' =&gt; $linkBlocks,
          ];
        },
      ];
    },
  ]
];