47

Eloquent's where() seems not working when comparing two column values. How to fix it?

Sample code:

->where('table_1.name', '=', 'table_2.name')

But works on:

->where('table_1.name', '=', 'john')
Jake Opena
  • 1,475
  • 1
  • 11
  • 18
  • you can accept my answer for further readers if it was helpful :) – Limon Monte Jun 05 '15 at 11:54
  • Possible duplicate of [Compare two colonne for some table with eloquent laravel](http://stackoverflow.com/questions/25311540/compare-two-colonne-for-some-table-with-eloquent-laravel) – Ivanka Todorova May 17 '16 at 07:27

3 Answers3

92

Escaping is unnecessary in this case, you can use whereRaw():

->whereRaw('table_1.name = table_2.name')
Limon Monte
  • 52,539
  • 45
  • 182
  • 213
77

You can use where column:

->whereColumn('table_1.name', 'table_2.name')
Pang
  • 9,564
  • 146
  • 81
  • 122
Carolyn Lim
  • 771
  • 5
  • 2
  • 1
    Just want to add that this method is only added in laravel 5. Use method in other answer if you are working on laravel 4 project like me. – cytsunny Sep 20 '16 at 09:35
  • 5
    You can also pass a comparison operator and/or an array of multiple conditions. eg, ->whereColumn([ ['first_name', '=', 'last_name'], ['updated_at', '>', 'created_at'] ]); – cdwyer Jul 24 '18 at 20:47
16

I figured it out. 'table_2.name' is interpreted as plain string and not a mysql table column.

Possible solutions:

  1. Wrap 'table_2.name'with \DB::raw()

    ->where('table_1.name', '=', \DB::raw('table_2.name'))
    
  2. Wrap the entire expression with whereRaw() (based on @limonte's answer)

    ->whereRaw('table_1.name = table_2.name')
    
Jake Opena
  • 1,475
  • 1
  • 11
  • 18