Often we face such scenarios where we have to create dynamic table header.Here i am sharing source code to create dynamic HTML table headers using PHP Laravel.
- Select Start and End Date From HTML Form
<form enctype="multipart/form-data">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Start date</label>
<input type="date" class="form-control" name="startDate">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="control-label">End date</label>
<input class="form-control" type="date" name="endDate">
</div>
</div>
</div>
</form>
<button type="submit">Submit</button>
- In Controller get Start Date and End Date
$startDate = $request->input('startDate');
$endDate = $request->input('endDate');
- Select all dates from table or any script between start Date and end Date.
$date =DB::table(‘SALE’)->select('DATE')
->whereBetween('DATE',[$startDate ,$endDate ])
->groupBy('DATE')->get();
- Query Statement
$query_initial = "select";
$query_mid = "";
4.Dynamic Headers Statement
foreach ($date as $item) {
$query_temp="sum(if(Day(DATE)= $item->DATE,SALE,0))as '$item->DATE',";
$query_mid = $query_mid . $query_temp;}
5.Main part of Query
$query_end = "EMP_ID as id,EMP_NAME
from Sale
join employes on Sale.EMP_ID =employes.id
where DATE between '$fromdate' and '$todate'
group by Sale.EMP_ID
order by EMP_NAME";
$Sale = $query_initial . $query_mid . $query_end;
- Convert this raw query to Laravel Query Statment
$EmpSale = DB::select($Sale);
- Return View
return view('your html page',compact('date','EmpSale')) ;
- HTML table code
- Create Table to show the dynamic header report
<table class="table" id="dataTables-example" align="center">
<thead>
<tr align="center" class="row">
<th>Employee Name</th>
2.Show Dynamic Headers
@php $room=0; @endphp
@foreach($date as $number)
<th ><b>{{$number->DATE}}</b></th>
@endforeach
</tr>
<tbody>
@foreach($EmpSale as $sale)
<tr>
<td>{{sale->EMP_NAME}}</td>
@php
for($x=0;$x<count($date);$x++){
$data = $date[$x]->INV_DT;
}
@endphp
<td>{{sale[$i]->$data }}</td>
@endforeach
</tr>
</tbody>
</table>