Level 24
Anyone?
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I want to get a total number of classes & total number of class bookings per studio (between certain dates). This query works to output [studio(with no. of classes)]->[classes]->[bookings]
So if I dd() I can expand bookings and see the array which i want to count.
$studios = \App\Studio::
withCount([
'classes'=>
function($q)use($start, $end){
$q->whereHas('classdates',function($q)use( $start, $end){
$q->whereBetween('datetime',[ $start, $end]);
});
}])
->with(['classes.classdates' =>
function($q)use($start, $end){
$q->whereHas('classes.classdates',function($q)use( $start, $end){
$q->whereBetween('datetime',[ $start, $end]);
})
->whereHas('classes.bookings');
}
,'classes.bookings'
])
->get();
I thought adding this (2nd bottom line) would work but it gives an error: Call to undefined method Illuminate\Database\Query\Builder::classes.bookings()
$studios = \App\Studio::
withCount([
'classes'=>
function($q)use($start, $end){
$q->whereHas('classdates',function($q)use( $start, $end){
$q->whereBetween('datetime',[ $start, $end]);
});
}])
->with(['classes.classdates' =>
function($q)use($start, $end){
$q->whereHas('classes.classdates',function($q)use( $start, $end){
$q->whereBetween('datetime',[ $start, $end]);
})
->whereHas('classes.bookings');
}
,'classes.bookings'
])
->withCount('classes.bookings')
->get();
I've tried a few ways of adding withCount() but it only seems to work on my first part...counting the classes
Please or to participate in this conversation.