1

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!

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),
        ];
      },
...
| improve this answer | |
  • 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 '18 at 10:27

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.