Search code examples
phphtmllaravel-blade

How to insert dinamic source for IMG element with blade in laravel from returned variable from view


I have a website with some products and I use blade for dinamic product page build. like this:

Route::get('/products/{product}', function ($product) {  
    return view('products/product',['name' => $product]);
});

I want to add images to my product page by getting all images from public/products/{$product} folder but it is not working for some reason. If I input the path manualy, it works fine, if I want to get it with the product variable, it does nothing.

Blade(this does not work):

  <section class="referenciak">
    <h1>Refenreciák</h1>
    @foreach(File::glob(public_path("images/products/{{$name}}").'/*') as $path)
      <img class="myImg" src="{{ str_replace(public_path(), '', $path) }}">
    @endforeach

  </section>

Blade(this works perfectly but I want to use the variable, what am I missing?):

  <section class="referenciak">
    <h1>Refenreciák</h1>
    @foreach(File::glob(public_path("images/products/somthing").'/*') as $path)
      <img class="myImg" src="{{ str_replace(public_path(), '', $path) }}">
    @endforeach

  </section>

Solution

  • You shouldn't need the curly braces to enclose the variable inside a @foreach. Try the following code:

      <section class="referenciak">
        <h1>Refenreciák</h1>
        @foreach(File::glob(public_path("images/products/$name").'/*') as $path)
          <img class="myImg" src="{{ str_replace(public_path(), '', $path) }}">
        @endforeach
      </section>