I'm getting matrix block content from an entry type which works fine for the most part. It's probably clearer to just paste in the code:
Current element api code:
$relationsData = [];
if($entry->relatedContent){
$index = -1;
foreach ($entry->relatedContent->all() as $block) {
switch ($block->type->handle) {
case 'relateContent':
$index++;
$relatedFeaturedEntries = $block->featured->first();
$relatedSubEntries = $block->related->first();
$relationsData[$index] = [
'title' => $relatedFeaturedEntries->title,
'url' => $relatedFeaturedEntries->url
];
$relationsData[$index]['subItems'] = [];
$relationsData[$index]['subItems'][] = [
'title' => $relatedSubEntries->title,
'url' => $relatedSubEntries->url
];
break;
}
}
}
Which outputs:
"relations": [
{
"title": "Testing workflow",
"url": "http://localhost/blah",
"subItems": [
{
"title": "Help & Guidance",
"url": "http://localhost/help-guidance"
}
]
},
{
"title": "Taking part in the blah",
"url": "http://localhost/blah",
"subItems": [
{
"title": "blah timeline",
"url": "http://localhost/blah"
}
]
},
{
"title": "Testing workflow",
"url": "http://localhost/blah",
"subItems": [
{
"title": "Completing on paper",
"url": "http://localhost/blah"
}
]
}
],
There should be more subItems
in each subItems
array but I am only getting the first because I'm fetching them using $relatedSubEntries = $block->related->first();
But nothing else works and just errors i.e. all()
or removing first()
Trying to get property of non-object
– Matt Simon May 23 '19 at 8:14