1

I'm using the Element API Plugin to create an API, with which I want to get entries related to one category, but dynamically with the category set in the Url.

What I have so far in the config/element-api.php:

<?php

use craft\elements\Entry;
use craft\helpers\UrlHelper;

return [
  'endpoints' => [
    'api/projects.json' => function() {
      $projectCategory = \Craft::$app->request->getQueryParam('projectCategory');

      // dump for test purpose
      var_dump($projectCategory);

      return [
        'elementType' => Entry::class,
        'criteria' => [
          'section' => 'projects',
          'relatedTo' => "{$projectCategory}",
        ],
        'elementsPerPage' => 2,
        'transformer' => function(Entry $entry) {
          return [
            'title' => $entry->title,
            'url' => $entry->url,
            'jsonUrl' => UrlHelper::url("projects/{$entry->id}.json"),
            'thumbnail' => $entry->projectThumbnail,
            'description' => $entry->projectDescription,
            'credits' => $entry->projectCredits,
          ];
        },
      ];
    },
  ],
];

When I go to http://domain.test/api/projects.json?projectCategory=category, I get the right value dumped, but the relatedTo doesn't seem to work. I get zero entries, although there are some related to a specific category.

Am I doing something wrong here?

2

Are you passing the projectCategory parameter as a string or ID? In any case, the relatedTo parameter will receive a string in your code, which might trip up the query. If the parameter is passed as an ID, passing it as an integer instead of a string might be enough:

'relatedTo' => (int) $projectCategory,

However, it might be cleaner to get the actual category element based on the ID and pass that to relatedTo. This will also allow you to check if the specified category actually exists (and optionally return an HTTP error for invalid parameters).

$criteria = ['section' => 'projects'];
$projectCategory = \Craft::$app->request->getQueryParam('projectCategory');
// this assumes the category is passed as an ID
$category = \craft\elements\Category::find()->id((int) $projectCategory)->one();
if ($category) {
    $criteria['relatedTo'] = $category;
}
1
  • 1
    Perfect, thanks for your reply. This works for me!
    – Malte
    May 20 at 13:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.