Home > Mobile >  Limit the number of <td> in a row using the laravel blade
Limit the number of <td> in a row using the laravel blade

Time:12-15

I have following code in my blade file $titleObject is a collection. Is there any way to limit the number(eg:- 3 items per row) of items per row. Please let me know if there is a better way to accomplish this than to write complex for loops.

<div  align="left"> 
  <!-- Navigation -->
  <header> <a href="">
    <table cellpadding="10" width="200" border="0">
      <tbody>
      @if($titleObject)
        <tr>
        @foreach($titleObject as $title)
          <td>{{$title->title}}</td>
           <td>&nbsp;</td>
           @endforeach
        </tr>
        @endif
       
      </tbody>
    </table>
    <h4 >&nbsp;</h4>
  </a></header>
</div>

CodePudding user response:

You can use Laravel Collection Chunk

<table>
    <tbody>
        @forelse ($titleObject->chunk(3) as $chunkedTitleObjects)
            <tr>
                @foreach ($chunkedTitleObjects as $title)
                    <td>{{$title->title}}</td>
                @endforeach
            </tr>
        @empty
            <tr>There is no data in table</tr>
        @endforelse
    </tbody>
</table>

Let me know the results.

CodePudding user response:

Assuming the key is starting at 0 and going up normally you can use it to determine every third element with the modulo operator. Something like this should work.

@if($titleObject)
  @foreach($titleObject as $key => $title)
    @if($key % 3 == 0)
     <tr>
    @endif
    <td>{{$title->title}}</td>
    <td>&nbsp;</td>
    @if($key % 3 == 2)
     </tr>
    @endif
  @endforeach
@endif

If the key is not equal to the index you could add a PHP variable or a normal for-loop that will count up and use the same logic as above.

CodePudding user response:

Here is a way to do it:

<tbody>
  @if($titleObject)
    @foreach($titleObject as $title)
      @if($loop->index % 3 == 0)
       <tr>
      @endif
    
      <td>{{$title->title}}</td>
      <td>&nbsp;</td>
    
      @if($loop->index % 3 == 0)
       </tr>
      @endif
    
    @endforeach
  @endif
</tbody>
  • Related