Divide laravel table into 4 columns from a single foreach

220 Views Asked by At

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

3

There are 3 best solutions below

1
kris gjika On BEST ANSWER

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.

0
Matthew Bradley On

This is expected. Your code basically performs the following:

FOR EVERY ITEM IN THIS ARRAY:
    MAKE A NEW TABLE ROW CONTAINING ONE COLUMN WITH THE OPTION NAME

Ideally, what you need is a collection of data with the fields you want to add in your table. For example:

$data = collect([[
    'name' => 'John',
    'age' => 18,
    'eye_colour' => 'brown'
  ],
  ...]);

@foreach($data as $person)
    <tr>
        <td>{{ $person->name }}</td>
        <td>{{ $person->age }}</td>
        <td>{{ $person->eye_colour }}</td>
    </tr>
@endforeach
0
Faramarz On

I don't know what exactly your $data is , but this probably going to solve your problem

@if( (($loop->iteration-1)  % 4) == 0 )

the code above closes the row (tr) and starts a new row (tr) after each 4 columns

it could be used like the following code

<table>
    <thead>
        <tr>
            <th>header 1</th>
            <th>header 2</th>
            <th>header 3</th>
            <th>header 4</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            @foreach($data as $key)
                @if( (($loop->iteration-1)  % 4) == 0 )
                    </tr>
                    <tr>
                @endif
                <td>{{$key}}</td>
            @endforeach()
        </tr>
    </tbody>
</table>