DDSameera's avatar

Loop row in bootstrap every 3 columns

Here is the way to create Bootstrap rows & columns using PHP language

Preview : https://snipboard.io/B23vxI.jpg

1st Method

 @for($i=1;$i<=12;$i++)

                    <!--Row Start-->
                        @if($colNo%3==0)
                            @php echo "<div class='row'>"; @endphp
                        @endif
                    <!--Row Start-->

                    <!--div Column Start-->
                        @php echo "<div class='col-4'>"; @endphp
                        @php echo $i; @endphp
                        @php echo "</div>"; @endphp
                    <!--div Column End-->

                    @php $colNo++;  @endphp

                    <!--Row End-->
                    @if($colNo%3==0)
                        @php echo "</div>"; @endphp
                    @endif
                    <!--Row End-->
                @endfor


2nd Method


                @foreach($backupFiles as $i=>$bf)


                        @if($colNo%3==0)
                            @php echo "<div class='row'>"; @endphp
                        @endif

                        @php echo "<div class='col-4'>"; @endphp
                        @php echo $i; @endphp
                        @php echo "</div>"; @endphp

                    @php $colNo++;  @endphp


                    @if($colNo%3==0)
                        @php echo "</div>"; @endphp
                    @endif
                  
                @endforeach

0 likes
6 replies
chaudigv's avatar

Is there a question @ddsameera? Or this code is more of a tip on how to create Bootstrap rows & columns using PHP language?

1 like
rodrigo.pedra's avatar
Level 56

col-4 will already wrap around every 3 columns. As Bootstrap 4 uses flex instead of floats for rows, there will be always 3 divs per row.

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">

<div class="row">
    @foreach(range(1, 12) as $record)
        <div class="col-4">{{ $record }}</div>
    @endforeach
</div>

If you really want to manually add a .row div every 3 elements, you can use blade's $loop variable:

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">

@foreach(range(1, 12) as $record)
    @if($loop->index % 3 === 0)
        <div class="row">
    @endif

        <div class="col-4">{{ $record }}</div>

    @if($loop->index % 3 === 0)
        </div>
    @endif
@endforeach

https://laravel.com/docs/8.x/blade#the-loop-variable

1 like
devingray_'s avatar

What about

@foreach($files as $file)


  @if($loop->index % 3 == 0)
      .... This is is every 3rd
  @endif

@endforeach

Please or to participate in this conversation.