First image of the manual sorted gallery

Hey everybody.
I use a custom order of my gallery for my articel:

<?php foreach($page->images()->sortBy('sort') as $image): ?>
<img src="<?= $image->url() ?>" alt="">
<?php endforeach ?>

On an overview for all articles I only want to show the first image.
<?= $articel->image() ?> It’s working but out of the box fetched by its filename I think.
In terms of performance, makes it sence to use the same loop but with ->first()? Or is there a better solution?

You don’t need a loop:

$firstImage = $article->images()->sortBy('sort')->first();
if ($firstImage) {
  // do stuff
}

Okay. So $bla->image() is just a shorthand for $bla()->images()->first() ?

Well, both will return the first image that exists in the file system. Although $page->image() does not use $page->images() internally.

So $page->image() without an argument fetches the first image from the file system. However, you can also pass an argument to this method to fetch a particular file $page->image('my-beautiful-image.jpg').

1 Like