Poxxac
Poxxac

Reputation: 103

Translate to Blade+Laravel a while loop

This code works, however in my learning of Laravel, I want to know if using Blade+Laravel syntax, can be better implemented

<?php
    $i = 1;
    while ($i <= (5 - $post->images->count())) {
        echo '<div class="col"> </div>';
        $i++;
    }
    ?>

Thanks

Upvotes: 0

Views: 12465

Answers (7)

pSouper
pSouper

Reputation: 21

In this specific case beacause you are looping count() you should use foreach, however you may also be interested @forelse:

@forelse($image as $img)
<div class="col"> {{ $img }}</div>
@empty 
<div class="col"> NO IMAGES </div>
@endforesle

Upvotes: 0

fayaz mohammad
fayaz mohammad

Reputation: 11

@php 
    $i = 0; 
@endphp 
@while (++$i <= (5 - $post->images->count())) 
    <div class="col"> 
    </div>
@endwhile

Upvotes: 1

Luca Di Lenardo
Luca Di Lenardo

Reputation: 21

I'm not sure is the best way to do, but works.

<?php $z = 0; ?>
@while ($z < 3)
  {{ "test".$z }} 
  <?php $z++ ?>
@endwhile

Upvotes: 1

Rwd
Rwd

Reputation: 35180

https://laravel.com/docs/5.5/blade#loops

I would suggest using a for loop instead of a while loop in this case:

@for ($i = 1; $i <= (5 - $post->images->count()); $i++)
    <div class="col"> </div>
@endfor

Upvotes: 7

xok
xok

Reputation: 1

The better solution would be to use @foreach

@foreach( $image as $post->images )

   <div class="col"> </div>

@endforeach

Upvotes: 0

Cedric
Cedric

Reputation: 5303

Yes, there is. Templating is made just for that, you can see how similar things are done with the docs : laravel blade : loops

@for ($i = 0; $i <  $post->images->count()); $i++)
    <div class="col"> </div>
@endfor

Upvotes: 0

Amarnasan
Amarnasan

Reputation: 15529

@for ($i = 0; $i <= (5 - $post->images->count()); $i++) 
   <div class="col"> </div>
@endfor

Upvotes: 0

Related Questions