Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

joshsalway's avatar

How to speed up this eloquent query in Laravel 5.2?

$countLeaseCommercial = DB::table('listings')
            ->join('properties', function ($join) {
                $join->on('listings.property_id', '=', 'properties.id')
                    ->where('properties.type', '=', 'Commercial')
                    ->where('listings.status', '=', 'Leased')
                    ->where('listings.user_id', '=', $this->user->id);
            })
            ->count();

How to speed up this query to be faster?

0 likes
2 replies
SilenceBringer's avatar

hi @joshsalway

You can play with the query itself. For example, rewrite it to something like:

$countLeaseCommercial = DB::table('properties')
    ->whereExists(function ($query) {
        $query->select(DB::raw(1))
            ->from('listings')
            ->whereRaw('properties.id = listings.property_id')
            ->where('properties.type', '=', 'Commercial');
    })
    ->where('listings.status', '=', 'Leased')
    ->where('listings.user_id', '=', $this->user->id)
    ->count();

Also you can make index in mysql columns you filtered on (properties -> type, listings -> status), and be sure that user_id and property_id are indexes too

Please or to participate in this conversation.