# Get first image of shuffled files collection?

**URL:** <https://forum.getkirby.com/t/get-first-image-of-shuffled-files-collection/19214>\
**Category:** Questions\
**Tags:** v3\
**Created:** [August 31, 2020, 5:28pm UTC](https://forum.getkirby.com/t/get-first-image-of-shuffled-files-collection/19214 "2020-08-31T17:28:18Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![JoSch](https://dub1.discourse-cdn.com/flex017/user_avatar/forum.getkirby.com/josch/32/10191_2.png) [@JoSch](https://forum.getkirby.com/u/JoSch)\
**Post date:** [August 31, 2020, 5:28pm UTC](https://forum.getkirby.com/t/get-first-image-of-shuffled-files-collection/19214/1 "2020-08-31T17:28:18Z")

</div>

I’m trying to get all images of a page, shuffle them and then output the URL of the first image of this shuffled collection.

Why is this throwing an error?

```
<?php 
  $imgs = $page->images()->shuffle();
  $previewImg = $imgs->first() 
?>

<img src="<?= $previewImg->url() ?>">

```

(The error thrown is »Call to a member function url() on null«)

---

<div class="post-metadata">

**Author:** ![texnixe](https://dub1.discourse-cdn.com/flex017/user_avatar/forum.getkirby.com/texnixe/32/5754_2.png) [@texnixe](https://forum.getkirby.com/u/texnixe)\
**Post date:** [August 31, 2020, 5:36pm UTC](https://forum.getkirby.com/t/get-first-image-of-shuffled-files-collection/19214/2 "2020-08-31T17:36:17Z")

</div>

If `$previewImg = $imgs->first()` doesn’t return an image, your call to url will fail with this error. Never call a class method without making sure you have an instance of that class.

Use an if statement to check first.

> **[$file](https://getkirby.com/docs/reference/objects/file#how-to-get-a-file-object)**
>
> The $file object provides a set of methods that can be used when dealing with a single image or other media file, like getting the URL or resizing an image. It also handles file meta data.

---

<div class="post-metadata">

**Author:** ![JoSch](https://dub1.discourse-cdn.com/flex017/user_avatar/forum.getkirby.com/josch/32/10191_2.png) [@JoSch](https://forum.getkirby.com/u/JoSch)\
**Post date:** [August 31, 2020, 5:41pm UTC](https://forum.getkirby.com/t/get-first-image-of-shuffled-files-collection/19214/3 "2020-08-31T17:41:46Z")

</div>

Thanks. I feel stupid now.

---

<div class="post-metadata">

**Author:** ![texnixe](https://dub1.discourse-cdn.com/flex017/user_avatar/forum.getkirby.com/texnixe/32/5754_2.png) [@texnixe](https://forum.getkirby.com/u/texnixe)\
**Post date:** [August 31, 2020, 5:53pm UTC](https://forum.getkirby.com/t/get-first-image-of-shuffled-files-collection/19214/4 "2020-08-31T17:53:18Z")

</div>

> [@JoSch](#):
>
> I feel stupid now.

No reason to feel stupid. It won’t happen to you again…
