Sorry if this is a stupid question but what in what context does isLast() need the collection? It seems sometimes I can use it without and it works as I expect but other time it does not.
Without a collection as argument, the reference for isLast(), isNext() etc. is the unfiltered, unsorted siblings collection. As soon as you want to use these methods on a filtered, sorted, merged collection, you need to pass this collection as parameter.
Thanks @texnixe, here was my case:
<?php $imageGalleries = $page->imageGalleries()->toStructure() ?>
<?php foreach ($imageGalleries as $imageGallery) : ?>
<div class="container<?= $imageGallery->isFirst() ? ' active' : ''; ?>">
<div class="row">
<?php $images = $imageGallery->images()->toFiles(); foreach($images as $image): ?>
<div class="<?= $image->isLast($images) ? 'col-auto pe-0' : 'col-auto'; ?>">
<img src="<?= $image->url(); ?>" alt="" class="">
</div>
<?php endforeach ?>
</div>
</div>
<?php endforeach ?>
I assumed that each structure entry would have its own collection of images, is this not the case?
In your case, with the images field inside the structure, yes. As I wrote above, passing the collection as argument is only relevant if you sort or filter:
Example:
$images = $page->images()->filterBy('template', 'gallery');
foreach ($images as $image) {
if ($image->isLast($images)) {
echo 'Is last of filtered collection';
}
}
Without passing the filtered collection as argument in this example, the file for which the condition would return true would be the last in the complete file siblings collection.
I may be misunderstanding but I was finding in my example that I needed to pass the collection for isLast() to work. Which seemed strange and compelled me to clarify.
Oh, yes, sorry. The files stored in the field are in fact a filtered collection (as compared to all files in the page).
That explains it! Thanks so much @texnixe.