Reputation: 257
I am trying to set color when my $key
value is changed. I mean I am generating a table when my $key
is changing. Now I want to set a different bg-color when the $key is changing and a new table created. Now the <th colspan="5">{{$key}}</th>
is changing and creating table for each $key
I need to set color that $key
is changing.
@foreach($lists as $key => $ser)
<table class="table table-striped table-bordered table-hover" id="sample_3">
<thead>
<tr>
<th colspan="5">{{$key}}</th>
</tr>
<tr>
<th> Destination</th>
<th> Services</th>
<th> Status</th>
<th> Time</th>
</tr>
</thead>
<tbody>
@foreach($ser as $s)
<tr>
<td style="background: rgb(176,224,230);"> TE 17 <br/>{{$s->sp}}</td>
<td> {{$s->dd}}</td>
<td> {{$s->ss}}</td>
<td> {{$s->dt}}</td>
</tr>
@endforeach
</tbody>
</table>
@endforeach
Upvotes: 0
Views: 914
Reputation: 9045
You can first add class from blade to group elements having similar value :
@php($prev = null)
@php($counter = 1)
@foreach($ser as $s)
@php
$counter = $s->key == $prev || is_null($prev) ? $counter : $counter + 1;
@endphp
<tr>
<td class="td_color_{{ $counter }}"> TE 17 <br/>{{$s->sp}}</td>
<td> {{$s->dd}}</td>
<td> {{$s->ss}}</td>
<td> {{$s->dt}}</td>
</tr>
@php($prev = $s->key)
@endforeach
This will give you following for the first column in each <tr>
:
<td class="td_color_1">...</td>
<td class="td_color_1">...</td>
<td class="td_color_2">...</td>
<td class="td_color_2">...</td>
<td class="td_color_3">...</td>
<td class="td_color_4">...</td>
<td class="td_color_5">...</td>
Then in your css you have colors for these :
<style type="text/css">
td.td_color_1 { background: red; }
td.td_color_2 { background: blue; }
td.td_color_3 { background: green; }
td.td_color_4 { background: yellow; }
td.td_color_5 { background: pink; }
</style>
Upvotes: 0
Reputation: 325
You can use a variable to store the value of $key
in each loop. Then you can check to see if the $key
is same as the previous one and change the color accordingly.
@php($prevvalue='')
@foreach($ser as $s)
<tr>
<td style="background: {{$s->key == $prevvalue ? 'oldcolor','newcolor'}}"> TE 17 <br/>{{$s->sp}}</td>
<td> {{$s->dd}}</td>
<td> {{$s->ss}}</td>
<td> {{$s->dt}}</td>
</tr>
@php($prevvalue = $s->key)
@endforeach
Upvotes: 1