So I’m currently doing this to get a specific image, basically cover/hero/featured images for blog posts.
<?php $posts = page()->children()->visible(); ?>
...
<?php foreach($posts as $post): ?>
...
<?php $heroImg = $post->images()->filterBy('name', '*=', 'cover'); ?>
<img src="<?php echo $heroImg->url() ?>" />
And it is outputting the path to the file however, instead of doing:
http://mydomain.com/whatever/cover.png
http://localhost/whatever/cover.png
I get this:
\storage\whatever\cover.png
c:\...\whatever\cover.png
Which leaves me with the image not showing up and being “broken”. So what might be going on?
Try
<?php $posts = page()->children()->visible(); ?>
...
<?php foreach($posts as $post): ?>
...
<?php $heroImg = $post->image()->findBy('name', '*=', 'cover'); ?>
<img src="<?php echo $heroImg->url() ?>" />
Unfortunately that doesn’t do anything, with that the src
just comes up empty. 
Ok, there is a typo up there it should beimages()
and also it seems that findBy
does not work with the filter methods. If your filenames are always the same, with just maybe different extensions you could try:
<?php $heroImg = $post->images()->findBy('name', 'cover'); ?>
That worked! Really great, many thanks! Would you, or anyone else, be able to explain what was going on?
I’m surprised your url
function worked, to be honest. filterBy
returns a collection, not an individual file object, so you should need to iterate through it. findBy
returns an individual item, so you can use $file
methods on it as expected.
1 Like