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

t0berius's avatar

using withCount() with scope

My products model is using the following relation:

public function sales()
{
    return $this->hasMany('App\Order');
}

Inside my Order model, there's the following scope:

public function scopeSuccessful($query)
{
    return  $query->whereIn('status_id', [0, 7, 10]);
}

Is there any way I can use the scope inside a withCount() query? Like:

Auth::user()->products()->withCount(['sales.successful'])->orderBy('products.created_at', 'desc')->paginate(15);

All in all I just want to make sure i don't have to hardcode the status ids into the withCount(), because something like this would work for sure too:

Auth::user()->products()::withCount(['sales' => function ($query) {
    $query->whereIn('status_id', [0, 7, 10]);
}])->get();

But it's just not that easy to maintain, so I would like to use the scope.

0 likes
1 reply
ftiersch's avatar
ftiersch
Best Answer
Level 28
Auth::user()->products()::withCount(['sales' => function ($query) {
    $query->successful();
}])->get();

:)

3 likes

Please or to participate in this conversation.