Murlidhar Fichadia Murlidhar Fichadia - 7 months ago 17
PHP Question

Get Days with zero total bookings too in laravel

I have list of bookings in one table and I have another table spots that has the event info such as : date, day , event_name, price, duration etc..

I need to groupBy bookings using days, which works fine but the problem comes when there are spots without any bookings and my join query matches spots and bookings table but if there arent any bookings for a given spot then the groupby for that particular day fails.

Example : I have spots on Mon, Tue and Wed. If there are no bookings for monday, I wont get a totalbooking count a zero. I dont get anything for that day. inshort, it doesnt exist.
Why I need is because : I have a progress bar on front-end which shows no. of bookings for each day, so if no bookings for given day I endup with no progress bar.

Controller :

//This query does not return bookings for tuesday because I dont have bookings.
$days = DB::table('spots')
->join('bookings','spots.id','=','bookings.spot_id')
->where('spots.event_id','=',$id)
->select('day',DB::raw('count(bookings.spot_id) as bookingcount'))
->groupby('spots.day')
->get();


View :

screenshot of the days progress bar, tuesday is not shown

@foreach($days as $day)
<div class="col-sm-6 col-md-3">
<div class="tablet tablet-stat">
<h4 class="tablet-header">{{ $day->day }}</h4>
<div id="circle">
<div class=" c100 p{{round(($day->bookingcount/$totalspace->totalspace)*100,0)}}">
<span> {{ round(($day->bookingcount/$totalspace->totalspace)*100,2) }} </span>
<div class="slice">
<div class="bar"></div>
<div class="fill"></div>
</div>
</div>
</div>
</div>
</div>
@endforeach


I am not really looking for a hack, like simply find the day that has no bookings and create another foreach loop to show those days with zero bookings. I prefer getting count as zero in my query.

Answer

Try it like this:

 $days = DB::table('spots')
            ->leftJoin('bookings','spots.id','=','bookings.spot_id')
            ->where('spots.event_id','=',$id)
            ->select('day',DB::raw('count(bookings.spot_id) as bookingcount'))
            ->groupby('spots.day')
            ->get();

*corrected the previous answer, didn't make much sense

An outer join should do what you want.