4

I'm trying to show a table in laravel blade same as the image below enter image description here

In the HTML Blade table To make a cell span more than one row, I use the rowspan attribute. But when I try to do it with foreach in blade view it not working perfectly. foreach loop return the team raw three times.

here is my blade code

@foreach($datas as $data)
  <tr>
  <td rowspan="3">{{$data->team_name}}</td>
<td>{{$data->name}}</td>
<td>{{$data->email}}</td>
<td>{{$data->phone}}</td>
</tr>
@endforeach

Please help.

1 Answer 1

5

Team row returning three times, because it's in the foreach, if rowspan is a static value you can try below code:

@foreach($datas as $key => $data)
  <tr>
     @if ($key == 0 || $key % 3 == 0)
         <td rowspan="3">{{$data->team_name}}</td>
     @endif
     <td>{{$data->name}}</td>
     <td>{{$data->email}}</td>
     <td>{{$data->phone}}</td>
  </tr>
@endforeach

Laravel 5.2 and up

For dynamic rowsapn, try below code:

@php
   $rowid = 0;
   $rowspan = 0;
@endphp
@foreach($datas as $key => $data)
  @php
     $rowid += 1
  @endphp
  <tr>
     @if ($key == 0 || $rowspan == $rowid)
         @php
             $rowid = 0;
             $rowspan = $data->how_many_members;
         @endphp
         <td rowspan="{{ $rowspan }}">{{$data->team_name}}</td>
     @endif
     <td>{{$data->name}}</td>
     <td>{{$data->email}}</td>
     <td>{{$data->phone}}</td>
  </tr>
@endforeach

change how_many_members property fits to your model field name.

Sign up to request clarification or add additional context in comments.

5 Comments

what should I do to make rowspan dynamic?
can you explain about your data models?
there is a table named teams which contain team name and how many members are register on there. another table named members which is connected to teams by foreign key
ok, you can use how many members registered field to achieve dynamic rowspan, is how many members registered field accessible via $datas collection??
can you give a example ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.