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

orest's avatar
Level 13

difference between whereColumn and where clause

i have the following table, model and scope

conversations

- id

reads

- id
- readable_id
- readable_type
- user_id
- read_at

users

- id

I have the following scope for the Conversation model

public function scopeWithRead($query)
{
    return $query->addSelect(['read_at' => Read::select('reads.read_at')
                ->whereColumn('reads.readable_id', 'conversations.id')
                ->whereColumn('reads.readable_type', 'App\Conversation')
                ->whereColumn('reads.user_id', auth()->id()),
        ]);
}

when i test this scope i get the correct results but when i actually try to use it from the front end i get 500 error

$conversations = Conversation::withRead()->get();

On the other hand, if i change from whereColumn to where, i get wrong results when i test it and the front end does not give any errors, however the results are wrong

public function scopeWithRead($query)
{
     return $query->addSelect(['read_at' => Read::select('reads.read_at')
                ->where('reads.readable_id', '=', 'conversations.id')
                ->where('reads.readable_type', '=', 'App\Conversation')
                ->where('reads.user_id', '=', auth()->id()),
        ]);
}

Any thoughts on what is wrong ?

0 likes
1 reply
MichalOravec's avatar

It has to be liek this

public function scopeWithRead($query)
{
    return $query->addSelect(['read_at' => Read::select('reads.read_at')
                ->whereColumn('reads.readable_id', 'conversations.id')
                ->where('reads.readable_type', 'App\Conversation')
                ->where('reads.user_id', auth()->id())
        ]);
}

whereColumn compare two column in the database, where there you have to pass your own value.

2 likes

Please or to participate in this conversation.