I just want to check each row in the column if data exist or not. The Idea is very simple. I wrote PHP date iteration in Controller to be matched with my date field in table.
Here are my tables:
tbl_user
-id_user
-name
tbl_timelog
-id_user
-date
-time_in
-time_out
My Controller:
function PrintReport()
{
$totdays=30;
for($x=1; $x<=$totdays; $x++){
$dates="2018-05-$x";
$data_list=PrintModel::join('tbl_user','tbl_user.id_user' ,'=','tbl_timelog.id_user')->orderBy('tbl_timelog.id_user','ASC')->where('date','=',$dates)->get();
}
return view('report/index', compact('date_list'));
}
If date found/matched, I want to get some value (time in - time out), then I'd like to pass the result to the view.
<?php
foreach ($data_list as $value) {
echo "</br>".$value->id_user." ".$value->time_in."-".$value->time_out."
</br>";
}
?>
But I dont know why the hell only last date (2018-05-30) is shown in view? Not each date in the field instead.
Please help
this is because every iteration replaced the previous one .. what you can do is in your controller ..
$data_list = [];
for($x=1; $x<=$totdays; $x++){
$dates="2018-05-$x";
$data_list[] = PrintModel::join('tbl_user','tbl_user.id_user' ,'=','tbl_timelog.id_user')->orderBy('tbl_timelog.id_user','ASC')->where('date','=',$dates)->get();
}
My suggestion is don't use queries insight for loop or foreach loop
function PrintReport()
{
$totdays=30;
$dates = [];
for($x=1; $x<=$totdays; $x++){
$dates[] ="2018-05-$x";
}
$data_list= PrintModel::join('tbl_user','tbl_user.id_user' ,'=','tbl_timelog.id_user')->orderBy('tbl_timelog.id_user','ASC')->whereIn('date',$dates)->get();
return view('report/index', compact('date_list'));
}
You need to make one array of all your date and then check the array value by where-clauses whereIn()
My suggestion is if you want to get the result on base of start date and end date of month then avoid the loop
$start = new Carbon('first day of this month');
$firstDate = $start->format('Y-m-d');
$end = new Carbon('last day of this month');
$lastDate = $end->format('Y-m-d');
->whereBetween('date',array($firstDate,$lastDate))
If you want to get result of sepcific month then you use whereMonth() and whereYear Function
->whereYear('date', $year)->whereMonth('date',$month);
With your query
$year = '2018';$month = '5';
$data_list= PrintModel::join('tbl_user','tbl_user.id_user' ,'=','tbl_timelog.id_user')->orderBy('tbl_timelog.id_user','ASC')->whereYear('date', $year)->whereMonth('date',$month)->get();