StuBlackett
StuBlackett

Reputation: 3857

Laravel Concat - Syntax or Access Violation

Trying to write an MySQL Query to search on users based on two columns :

first_name

surname

I'd like to Concatenate first_name and surname as name and then write a search query based on that.

I've currently written some PHP code, But I keep getting the error :

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '%?%' at line 1 (SQL: select users.* from users where CONCAT(first_name, ' ', surname) LIKE %Stu%)

My current PHP code is as follows :

// Search Based on Q..
$q = $request->input('q');

$results = User::select('users.*')->WhereRaw("CONCAT(`first_name`, ' ', `surname`) LIKE %?%", [$q])->get();

I suspect I'm just getting the syntax wrong, But any help would be appreciated.

Thank You!

Upvotes: 1

Views: 303

Answers (2)

user5350813
user5350813

Reputation:

two errors in your query first as fullname not mention and second like operator.. i have fix these errors

$q = $request->input('q');
     $results = User::select('users.*')
     ->WhereRaw("CONCAT(`first_name`, ' ', `surname`) as fullname
     LIKE ?", ['%' . $q . '%'])->get();

Upvotes: 1

u_mulder
u_mulder

Reputation: 54796

Move % to parameter:

$results = User::select('users.*')
    ->WhereRaw("CONCAT(`first_name`, ' ', `surname`) LIKE ?", ['%' . $q . '%'])
    ->get();

Upvotes: 2

Related Questions