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

bufferoverflow's avatar

Laravel having() query not returning expected result

Hi,

Having the following scope query:

    public function scopeAvailable($query)
    {
        $query->select('id', 'available_replies')
            ->withCount(['emails' => function (Builder $query) {
                $query->whereDate('created_at', Carbon::today());
            }])
            ->having('emails_count', '<', 'available_replies');
    }

I execute this query:

$availableAccounts = Account::available()->get();

// The database has a model with:
'available_replies' => 1,
'emails_count' => 0

// But it prints print $availableAccounts
Illuminate\Database\Eloquent\Collection {#2196 ▼
  #items: []
}

Why is having('emails_count', '<', 'available_replies') failing? It should be translated to: having(0, '<', 1), right?

0 likes
1 reply
CorvS's avatar
CorvS
Best Answer
Level 27

@bufferoverflow having doesn't allow comparing two columns, the second (or third) parameter is meant to be a value (e.g. having('emails_count', '<', 100)). Right know you are checking if the email count is lesser than the string "available_replies". You can use havingRaw to achieve what you want.

havingRaw('emails_count < available_replies')
1 like

Please or to participate in this conversation.