Ad

How To Display AttachMany Images In Frontend In Octobercms?

- 1 answer

This should be pretty straight forward but cant figure out what is missing. I am trying to display attachMany in front-end but it is not working.

It is working fine in the back-end and only works in the front-end when i change it to attachOne

    `{% for image in ads.gallery %}
   <img src="{{ image.gallery.thumb(100, auto) }}">
  {% endfor %}`

I expect it to display all the images uploaded in a front-end gallery

Ad

Answer

In the relation attachOne, It is working because you are trying to get gallery even after using for loop via {{ image.gallery.thumb(100, auto) }}.

For attachMany relation, you will need to do something like this.

{% for image in ads.gallery %}
   <img src="{{ image.thumb(100, auto) }}">
{% endfor %}

For more information, visit this official documentation link Here.

And, if you have still any doubts, please comment.

EDIT

So you are using this query on the page,

$this['ads'] = Advert::whereHas('cats', function ($query) use ($slug) 
              { 
                 $query->where('slug',$slug); 
              })->get();

Now, based on your query, you are retrieving multiple ads on the page, So you will need to write one for loop for your ads to show on the page and on loop for gallery

{% for ad in ads %}
   //to get values from you can do {{ad.name}}
   //to get gallery values from particular ad, you will need to write for loop again(because you have used relation attachMany) 
    {% for image in ad.gallery %}
       <img src="{{ image.thumb(100, auto) }}">
    {% endfor %}
{% endfor %}

And to retrieve gallery, you should use eager loading, So your query should be

$this['ads'] = Advert::with('gallery')->whereHas('cats', function ($query) use ($slug) 
              { 
                 $query->where('slug',$slug); 
              })->get();
Ad
source: stackoverflow.com
Ad