Jake Opena
Jake Opena

Reputation: 1525

Laravel Eloquent Compare Column Values

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')

Upvotes: 48

Views: 58593

Answers (3)

Carolyn Lim
Carolyn Lim

Reputation: 791

You can use where column:

->whereColumn('table_1.name', 'table_2.name')

Upvotes: 79

Jake Opena
Jake Opena

Reputation: 1525

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')
    

Upvotes: 18

Limon Monte
Limon Monte

Reputation: 54459

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

->whereRaw('table_1.name = table_2.name')

Upvotes: 93

Related Questions