Eloquent WHERE LIKE clause with more than two columns

320
August 20, 2017, at 09:44 AM

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.

Answer 1

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%')"
Rent Charter Buses Company
READ ALSO
create as in 2 meta_key using mysql

create as in 2 meta_key using mysql

Assums table mysql from wordpress like this:

274
Multiple relations to the same model: from CakePHP 2.x to CakePHP 3.x

Multiple relations to the same model: from CakePHP 2.x to CakePHP 3.x

My attempt to apply this example to CakePHP3: tables users and messages (id, user_id, recipient_id, body) with two foreign keys to id in users

197
Php Int64/Long to bits and Edit parts of the bits

Php Int64/Long to bits and Edit parts of the bits

I am struggling with solving the problem of converting a long(Int64) to bits and modifiying content of it

285
How to set up an ODBC for MS Access 2016?

How to set up an ODBC for MS Access 2016?

I am fairly new to databases and also my English is very bad so don't mind my silly mistakesI am using:

280