Oscar Muñoz Oscar Muñoz - 2 months ago 21
PHP Question

Eloquent WHERE LIKE clause with more than two columns

I've been trying to do a query in Laravel that in raw SQL will be like this

"SELECT * FROM students WHERE (((students.user_id)=$id) AND (((students.name) Like '%$q%') OR ((students.last_name) Like '%$q%') OR ((students.email) Like '%$q%')))")

I follow this thread (Eloquent WHERE LIKE clause with multiple columns) and it worked fine, but only with two columns Ej:

$students = student::where(user_id, Auth::id())
->whereRaw('concat(name," ",last_name) like ?', "%{$q}%")

But if I add more than two columns then the resultant variable is always empty, no matter if what is in the variable $q match with one or more columns:

$students = student::where(user_id, Auth::id())
->whereRaw('concat(name," ",last_name," ",email) like ?', "%{$q}%")

I am pretty sure I am missing something but i can't find what it is. Thanks in advance.

Answer Source

You can do something like this:

$students = student::where('user_id', Auth::id())->where(function($query) use ($q) {
    $query->where('name', 'LIKE', '%'.$q.'%')
        ->orWhere('last_name', 'LIKE', '%'.$q.'%')
        ->orWhere('email', 'LIKE', '%'.$q.'%');

The above Eloquent will output SQL similar to

"SELECT * FROM students WHERE students.user_id = $id AND (students.name like '%$q%' OR students.last_name Like '%$q%' OR students.email Like '%$q%')"