Random background image every refresh

I try to set a background image that every time that the page loads it takes a different image from a list of images that the client uploaded through the panel.

in the home page yml I have this section:

    type: fields
        label: Images for home gallery
        type: files
        layout: cards
          cover: true

I want to call to one of these images randomly to set it as a background image.
I use this tutorial and this is my code in the page template:

<div class='haunted-background'>
    <img src="<?= page('home')->imges()->shuffle()->first()->toFile()->url()?>" >

The result that I get is just the first image in the list. nothing random about it :slight_smile:
If I change the order of the images I get the new first image.

Any idea what went wrong?

Thank you!

You want to turn the field value into a files collection first:

  $images = page('home')->imges()->toFiles()
  $randomImage = $images->shuffle()->first()
<img src="<?= $randomImage->url() ?>">
1 Like

works like a charm :slight_smile:
thanks a lot