$data = DB::table('Table') ->select(DB::raw('Table.sales as sales')) ->whereBetween('Table.date', [$startDate, $endDate]) ->orWhereNull('Table.date')
this said the date column is not nullable. so there will always be a date.
am I missing somethnig?
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
If I have table Table with the following structure:
Schema::create('Table', function (Blueprint $table) {
$table->increments('id');
$table->date('date');
$table->integer('sales')->default(0);
I am able to query it and retrieve data for a range of dates like this:
// assume $startDate and $endDate exist and are valid
$data = DB::table('Table')
->select(DB::raw('Table.sales as sales'))
->whereBetween('Table.date', [$startDate, $endDate])
But what I would really like is to get a record for every date in the date range, even if there is no matching entry for some dates (sales can be 0, or null in that case).
Does anyone have any suggestions on the best way to go about this? I've thought about making a static table of dates and using it as the left side of a join. It seems like a common pattern though, so I'm curious to know what others have tried, or if there's an obvious solution I've missed.
Thank you for your time.
First, convert your date range into array of all dates comes in between like this
$period = new DatePeriod(new DateTime('2017-11-01'), new DateInterval('P1D'), new DateTime('2017-11-03 +1 day'));
foreach ($period as $date) {
$dates[] = $date->format("Y-m-d");
}
var_dump($dates);
//output will be {"2017-11-01","2017-11-02","2017-11-03"}
Now use foreach loop and grab the results then form your output like this
$result = [];
foreach($dates as $date){
$sales= DB::table('Table')->whereDate('date',$date)->pluck('sales');
if($sales){
$result[] = array($date =>$sales);
}else {
$result[] = array($date =>0);
}
}
return $result;
Please or to participate in this conversation.