2

I have an asset field in my current project with the handle postImage, containing multiple image files. In my element-api endpoint, I wish to access the url of the first file only.

I tried the following code:

$imgs = $entry->postImage;
$imgUrl = $imgs[0]->getUrl();

The resulting console error message says:

500 (Call to a member function getUrl() on string)

Looping through the array works fine, but I don't want all image urls, just the first one.

It's probably very easy, but that ties a knot my brain. I don't understand where the array is being converted to a string, can anyone hint me to the solution?

Thanks a lot!

3 Answers 3

2

you could use array_values() to fetch the first image:

...
      'transformer' => function (Entry $entry) {
        foreach ($entry->images as $image) {
          $images[] = $image->url;
        }
        return [
          'images' =>  array_values($images)[0],
        ];
      },
...

or use reset()

...
      'transformer' => function (Entry $entry) {
        foreach ($entry->images as $image) {
          $images[] = $image->url;
        }
        return [
          'images' =>  reset($images),
        ];
      },
...
1
  • Thanks a lot! reset() works fine. When I use array_values() I get the following error: 500 (Undefined offset: 0). When I dump the entire array, the key 0 seems to be present. It works with reset() so I'm fine, but I'm curious why the other solution doesn't work.
    – Anthronaut
    Sep 13, 2018 at 10:27
1

You can do something like this:

'transformer' => function(craft\elements\Entry $entry) {
    $image = $entry->photos->one();

    return [
        'image' => $image ? $image->url : null,
    ];
},

More info here.

1

I was wondering this myself, and I figured there had to be an easier built-in Craft solution rather than using pure PHP like HendrikEng suggested, and it turns out there is! Just use $entry->assetsFieldHandle->one()->url:

use craft\elements\Entry;

return [
    'endpoints' => [
        'entries.json' => function() {
            return [
                'elementType' => Entry::class,
                'elementsPerPage' => 10,
                'criteria' => [
                    'section' => 'blog'
                ],
                'transformer' => function(Entry $entry) {
                    return [
                        'id' => $entry->id,
                        'title' => $entry->title,
                        'url' => $entry->url,
                        'mainImg' => $entry->mainImg->one()->url
                    ];
                }
            ];
        }
    ]
];

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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