What makes you say that it's sub-optimal? Is it slow?
I'm a little confused about the fact that your Blade file is using the Listings model and you're asking about optimizing a query that is structured around a Projects model.
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I need following totals and I am using in blade as
@php
$activelistings = App\Models\Listings::where('project_id',$item->id)
->where('status',1)->latest()->count();
$totalinprogress = App\Models\Listings::where('project_id',$item->id)->where('status',1)
->where('dealstatus','inprogress')->latest()->count();
$totalclosed = App\Models\Listings::where('project_id',$item->id)
->where('status',1)->where('dealstatus','closed')->latest()->count();
@endphp
My query in the controller is
$projects = Projects::withCount('listings')
->withCount('reviews')
->withAvg('reviews', 'rating')
->whereHas('city', function ($query) {
$query->where('status', 1);})
->leftJoin('reviews', function ($join) {
$join->on('reviews.project_id', 'projects.id')->where('status', 1);})
->groupBy('projects.id')
->orderByDesc('reviews_count')
->paginate(15);
My projects model with listing relation is :
public function listings(){
return $this->hasMany(Listings::class, 'project_id', 'id');
}
How can I optimise this query ?
@FounderStartup I actually did. I just removed the stuff that wasn't new so you could better see what I did. Here I added "in progress". Just add the rest in the same way
$projects = Projects::withCount('listings')
->withCount(['listings as in_progress_count' => function ($query) {
$query->where('status', 1);
}])
->withCount('reviews')
->withAvg('reviews', 'rating')
->whereHas('city', function ($query) {
$query->where('status', 1);})
->leftJoin('reviews', function ($join) {
$join->on('reviews.project_id', 'projects.id')->where('status', 1);})
->groupBy('projects.id')
->orderByDesc('reviews_count')
->paginate(15);
Please or to participate in this conversation.