Skip to content
Advertisement

Compare two columns with ‘LIKE’ Operator in SQL / Laravel

I’m trying to compare two columns from a table. In which i have to check the email is containing his mobile number or not.

TableName:- Table1
TableColumns:- id,email,MOB

Ex.

SQL:

 'SELECT * FROM Tabel1 WHERE email LIKE %MOB%'

Laravel :

Tabel1::whereColumn('email', 'LIKE','%MOB%')->get();

I have Tried this above query but it is showing syntax error.

Advertisement

Answer

Lets start by answering you question SQL-wise, anything in quotes is a literal to SQL, so you need to use column reference and add the wildcard symbols. You can do that like this:

SELECT * FROM Table1 WHERE email LIKE CONCAT('%', MOB, '%');

Now lets look at Laravel now, the 3rd argument to where expects a literal value not another column. You can overcome this via either whereRaw or DB::raw:

Table1::whereRaw("email LIKE CONCAT('%', MOB, '%')");

or

Table1::where('email', 'LIKE', DB::raw("CONCAT('%', MOB, '%')"));
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement