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

Chaeril's avatar

withCount N+1 query

I had a query like this, and Sentry detects it as an N+1 problem. what's the better way to do it?, I might use $appends but I don't want to count them everywhere I use the Brand model.

        $this->brands = Brand::active()
            ->withCount(['ads' => function ($query) {
                $query->active();
            }])
            ->orderBy('ads_count', 'desc')
            ->orderBy('brand_name', 'asc')
            ->pluck('brand_name', 'brand_id')->sort();
0 likes
7 replies
Chaeril's avatar

@aruszala Yes, i was putting them on the select box, i just need the id and name.

1 like
Snapey's avatar

Not sure this code will cause any n+1 issues.

You sure you are not triggering it in a view?

1 like
Chaeril's avatar

@Snapey seems you were right, the code was inside a component, and I was calling the same component twice for the desktop, and the mobile version. maybe i should wrap them inside a bigger component.

1 like
Snapey's avatar
Snapey
Best Answer
Level 122

@Chaeril or use a view composer so that the data is available to both components.

1 like

Please or to participate in this conversation.