I defined a scope function in an Eloquent model that uses withCount in the query, I also define an unit test for this function that works properly but when I use it in my controller it throws the exception error which is
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'unused_count' in 'where clause' (SQL: select * from `coupons` where `unused_count` > 0)
Here are my eloquent model functions:
public function unsed(): BelongsToMany
{
return $this->belongsToMany(User::class, 'user_coupon')
->wherePivot('discount', '=', 0);
}
public function scopeAvailable(Builder $query): Builder
{
return $query->where(function ($coupons) {
return $coupons
->withCount('unused')
->where('quantity', '>', 0)
->orWhere('unused_count', '>', 0 );
});
}