Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eloquent WHERE LIKE clause with more than two columns

Tags:

php

laravel

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}%")
         ->paginate(9);

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}%")
         ->paginate(9)

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

like image 913
Oscar Muñoz Avatar asked Aug 19 '17 21:08

Oscar Muñoz


1 Answers

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.'%');
})->paginate(9);

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%')"
like image 140
mbozwood Avatar answered Oct 15 '22 00:10

mbozwood