Select rows having 2 columns equal value in laravel Query builder

I want to write a query that selects rows where 2 attributes from 1 object have equal value.

This will be an example of this in raw SQL:

Select * from users u where u.username = u.lastname 

Does laravel have any methods that take 2 column names as parameters and return matching results?

+5
source share
2 answers

You need a DB::raw expression:

 DB::table('users') ->where('username', '=', DB::raw('lastname')) ->get(); 

The only thing DB::raw does is to force the query interpreter not to process 'lastname' like any other string value, but simply interpolate it in SQL as it is.

http://laravel.com/docs/queries#raw-expressions

+23
source

In Laravel 5, now whereColumn for this, for cleaner code:

 Users::whereColumn('username', 'lastname')->get(); 
+1
source

Source: https://habr.com/ru/post/1203051/


All Articles