skip to Main Content

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
HOW I WANT IT

2

Answers


  1. 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
    
    Login or Signup to reply.
  2. 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

    <tr>
      @foreach($data as $key)
        <td>{{$key->option_name}}</td>
      @endforeach()
    </tr>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search