Testing for images by filename

I’m trying to include a slider on my posts page, if there are images with “slider” in the filename. I can get the code to work, but my “if” statement doesn’t. What am I missing?

<?php if ($slider = $page->images()->filterBy('filename', '*=', 'slider')): ?>
<div class="slider" data-arrows="true">
	<ul class="slides">
		<?php foreach ($slider as $image): ?>
		<li>
			<img alt="Image" src="<?= $image->url() ?>" />
		</li>
		<?php endforeach ?>
	</ul>
</div>
<?php endif ?>

You can use isNotEmpty() to test if a collection has items:

<?php 
$slider = $page->images()->filterBy('filename', '*=', 'slider');
if ($slider->isNotEmpty()): ?>
<div class="slider" data-arrows="true">
	<ul class="slides">
		<?php foreach ($slider as $image): ?>
		<li>
			<img alt="Image" src="<?= $image->url() ?>" />
		</li>
		<?php endforeach ?>
	</ul>
</div>
<?php endif ?>

With your if statement, you only test if the collection exists, but this will return true because the collection exists even if it has no items.

Makes total sense. I was trying to add hasImages() at the end and wasn’t successful with that either.

Is it possible to add this filter into a collection?

Yes, you can totally do that. But you cannot pass a page as a variable to a collection. The better option would be a page model or a controller.

Awesome. I’m just trying to wrap my head around the best way to reduce the code in the template.

So I’ll build a collection looking for those images. Then I can load those images in my post.php controller. Do I test for the existence in the controller or on the post.php template?

See my edit above.

For anyone watching, I ended up creating a “post” controller and this code to load the slider images:

return function($page) {
$slider = $page->images()->filterBy('filename', '*=', 'slider');

return compact('slider');
}