phplaravelcss-tables

Divide laravel table into 4 columns from a single foreach


I have a foreach loop that has data. I am using a foreach loop to echo the data out into a table.

@foreach($data as $key)
 <tr>
   <td>{{$key->option_name}}</td>
</tr>
@endforeach()

This gives me a table with one column and 1 row of data. This table only has one data field and instead of one long list of data, i want it spread over 4 columns.

I would like to have 4 columns so the table looks nice and neat.

Please see attached example image.

How it is now CURRENT

What i am trying to achieve, after the 4 columns if there is more data then it starts the next row with 4 columns. HOW I WANT IT


Solution

  • instead of creating a new row and column for each data point, simply don't create a new row by putting the tr outside the loop. Assuming your $data is a collection, we can use the chunk(size: 4) method to create collections of specified size out of the original $data.

    This way every $size items we create a new row with $size columns.

    @foreach($data->chunk(4) as $chunk)
      <tr>
        @foreach($chunk as $key)
          <td>{{$key->option_name}}</td>
        @endforeach()
      </tr>
    @endforeach
    

    If $data is an array we can use the array_chunk function instead.