Home > Blockchain >  Using variables in laravel blade template
Using variables in laravel blade template

Time:10-03

Could anyone help me to understand how to use variables in the following case:

@for($i = 0; $i < 3; $i  )
                    @if(isset($images->image_$i_url))
                        <div  >
                            <img src="{{ Storage::url($images->image_$i_url) }}" alt="image" style="width: 128px;">
                        </div>
                    @endif
                    <div >
                        <div >
                            <div >
                                <input name="product_image_{{ $i }}" type="file"  id="product_image_{{ $i }}">
                                <label  for="exampleInputFile">Choose file</label>
                            </div>
                        </div>
                        @error("product_image_{{ $i }}")
                        <div >{{ $message }}</div>
                        @enderror
                @endfor

It doesn't work for $i

CodePudding user response:

If I get correctly, you have a problem with this line:

{{ Storage::url($images->image_$i_url) }}

Particularly:

$images->image_$i_url 

Which is not solved to:

$images->image_0_url
$images->image_1_url
...

Technically, you cannot put $ symbols as part of property name when you call it.

Therefore, a trick is by using '{}'

$images->{'image_' . $i . '_url'};

Full line example:

<img src="{{ Storage::url($images->{'image_' . $i . '_url'}) }}" alt="image" style="width: 128px;">

CodePudding user response:

You just want to iterate on three images?

@foreach(['image_1_url', 'image_2_url', 'image_3_url'] as $image)
   @if(isset($images->$image))
      <div  >
        <img src="{{ Storage::url($images->$image) }}" alt="image style="width: 128px;">
      </div>

// etc as before

@endforeach

CodePudding user response:

Try this instead. Loop through the collection of images. Whenever you want to reference the index of the loop, use $loop->index. This will scale better than using a hard-coded for loop.


@foreach ($images as $image)

     @if ($image->url)

          <div  >
               <img src="{{ Storage::url($image->url) }}" alt="image" style="width: 128px;">
          </div>
          <div >
               <div >
                    <div >
                         <input name="product_image_{{$loop->index}}" type="file"  id="product_image_{{$loop->index}}">
                         <label  for="exampleInputFile">Choose file
                         </label>
                     </div>
               </div>
               @error("product_image_{{$loop->index}}")
                   <div >{{ $message }}</div>
               @enderror
          </div>
     @endif     
@endforeach

  • Related