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

Christofer's avatar

Since when does Eloquent Builder where function not able to compare 2 fields?

Does anybody know Since when does Eloquent Builder "where" function begin to not be able to compare 2 date fields?

Example: User::where('updated_at', '>', 'created_at') // this doesn't return the expected results

Example: User::whereColumn('updated_at', '>', 'created_at') // whereColumn returns the expected results

whereColumn is used to be able to use another field as the 2nd or 3rd param

I'd like to know since when? Or, since which Laravel version.

0 likes
5 replies
LaryAI's avatar
Level 58

According to the Laravel documentation, the where method can be used to compare two columns by passing the column names as the values. So in the example provided, the correct syntax would be:

User::where('updated_at', '>', DB::raw('created_at'))->get();

This will compare the updated_at column with the created_at column and return the expected results.

It's unclear when this behavior changed, but it's possible that it was a recent change in Laravel version 8.0.

1 like
Snapey's avatar
Snapey
Best Answer
Level 122

Where has never supported comparing two columns.

WhereColumn has been present since version 5.2

1 like
Christofer's avatar

@Snapey Thanks for that info. Concerning as I have a couple of apps still using L4.2 What happens if I use where() with 2 columns? And, What happens if I use where() with 2 date type columns?

kokoshneta's avatar

@Christofer As you’ve seen, what happens is that the query doesn’t work. The query will end up being SELECT * FROM table WHERE updated_at > 'created_at', comparing the column value to a string.

I’ve never used Laravel 4.2, but in later versions, I would use whereRaw():

User::whereRaw('updated_at > created_at')->get();
1 like
Snapey's avatar

@Christofer As mentioned, you cannot compare two columns in the earlier versions without writing your own raw query

1 like

Please or to participate in this conversation.