Skip to content Skip to sidebar Skip to footer

Laravel Merge Two Columns When Querying Like

I have a search input ?search=xxxx I have two columns in my database first_name and last_name. I want the search to work for both of them, for example if my input is John Smith the

Solution 1:

There are multiple problems:

  • You can't wrap columns in single quotes. Use double quotes (or no quotes at all).
  • You can't access derived columns like fullname in the WHERE clause.
  • whereRaw() only has two parameters, the SQL string and an array of bindings.

Use this:

$customers->where(DB::raw('concat("first_name", "last_name")'), 'ilike', '%'.$text.'%');

Solution 2:

I'm not sure what it is you are using based on how you are writing your code but if it is sql this might be what you are after...

DECLARE@cust_name VARCHAR(100) ='john smith'-- users inputDECLARE@first_name VARCHAR(50) =SUBSTRING(@cust_name, 1, CHARINDEX(' ', @cust_name) -1)
DECLARE@last_name VARCHAR(50)  =SUBSTRING(@cust_name, CHARINDEX(' ', @cust_name) +1, 8000) 


SELECT CONCAT(c.FirstName,c.LastName)
FROM 
    customers c
WHERE
    c.FirstName =@first_name
    AND c.LastName =@last_name

Post a Comment for "Laravel Merge Two Columns When Querying Like"