Query field from a structure field in controller

In my articles controller I want to query all topics from the articles. But… the topic-field is a structure-field with both a topicname and a topiclink. But I only want to query the topicnames.

this is how my controller looks like:

<?php
return function($page, $kirby, $site) {
        
    // fetch the basic set of pages
    $articles = $page->children()->listed()->flip()->sortBy(function ($page) {
        return $page->start();
    }, 'desc');

    // fetch all
    $tags = $articles->pluck('tags', ',', true);
    $topics = $articles->pluck('researchtopics', ',', true);

    // add the tag filter
    if($tag = param('tag')) {
        $articles = $articles->filterBy('tags', urldecode($tag), ',');
    }
    // add the tag filter
    if($topic = param('topic')) {
        $articles = $articles->filterBy('topic', urldecode($topic), ',');
    }


    // apply pagination
    $articles   = $articles->paginate(30);
    $pagination = $articles->pagination();

    $data = compact(
        'articles', 
        'topics', 'topic',
        'pagination', 'metatitle',
    );

    return a::merge(
        $seo, $data
    );


};
?>

And this is the structure-field in my blueprint:

researchtopics:
    label: Research Topics
    type: structure
    fields:
      topicname:
        label: topic name
        type: text
      topiclink:
        label: topic link
        type: url

Obviously $topics = $articles->pluck('researchtopics', ',', true); doesn’t do the trick.

Also, It’s been a while working with Kirby and I seem to have lost some basic php knowledge which might be helpfull here…

You have to loop through the articles and for each article, convert the structure field value to a structure collection, then pluck the relevant field and merge the values.

$topics = [];

foreach ($articles as $article) {
  $articleTopics = $article->researchtopics()->toStructure()->pluck('topicname', ',', true);
  $topics =  array_merge($topics, $articleTopics);
}

That makes perfect sense! As always, thanks for the quick response :slight_smile: