Shuffle files in homepage

Hi,

I’m trying to use the ->shuffle() function to get a random image from my homepage blueprint.

I have created the under the folder site/blueprints/pages/ a home.yml inside. I have differents tabs, with some text fields, files fields and so on.

I want to use the shuffle on that particular files fields:

    fields:
      gallery:
        label:
          fr: galerie
          en: Gallery
        type: files
        accept: image/jpeg, image/png, image/gif
        layout: cards
        template: image
        translate: false

To output the random image I use the following code:

$site->homePage()->gallery()->shuffle()->first()->toFile();

But the same and first image always appears… Because I have other images in the others tabs I can’t use the ->images() instead of the ->gallery()

Any help would be grateful!

You have to convert the field values to a files collection first using toFiles() as described in the documentation for the field.

$site->homePage()->gallery()->toFiles()->shuffle();

If you only want to get the first image of the shuffled collection:

// use if statement to make sure we have an image object
if ($image = $site->homePage()->gallery()->toFiles()->shuffle()->first()) {
  echo $image;
}

Thank you, I see now the logic behind the ->toFiles.