Home > Enterprise >  Prevent foreach from loop html tag multiple time in blade laravel
Prevent foreach from loop html tag multiple time in blade laravel

Time:11-15

I'm trying to loop data using foreach and I want to skip the html tag after the first item being looped.

I've tried like the code bellow, but the html tag <p> still being looped multiple time. What I want is the <p> tags only looped once

@foreach ($store_icon as $key => $icon)
   @if ($key < 1)
       <p class="available-at">Also available at:</p>
   @endif
   <a href="{{ $store->product_url }}" target="_blank" style="margin-right: 2px"></a>
@endforeach

Result example:

What I want is like this:

Also Available at
- Product 1
- Product 2

But using the code above it resulted like this:

Also Available at
- Product 1
Also Available at
- Product 2

Thanks

CodePudding user response:

I am not sure why it is not working, It must work and working the same code for as well, you can try --

@foreach ($store_icon as $key => $icon)
   @if ($key == 0)
       <p class="available-at">Also available at:</p>
   @endif
   <a href="{{ $store->product_url }}" target="_blank" style="margin-right: 2px"></a>
@endforeach

OR you can use like this

@if(!empty($store_icon))
<p class="available-at">Also available at:</p>
    @foreach ($store_icon as $key => $icon)
       <a href="{{ $store->product_url }}" target="_blank" style="margin-right: 2px"></a>
    @endforeach
@endif

CodePudding user response:

Whats problem? Just take it out from loop.

<p class="available-at">Also available at:</p>
@foreach ($store_icon as $key => $icon)
   <a href="{{ $store->product_url }}" target="_blank" style="margin-right: 2px"></a>
@endforeach
  • Related