Reputation: 4421
I am trying to build a query in Laravel 4 using the Eloquent ORM that simply matches all fields in the criteria. I have the below code which at present returns data that matches ANY of the criteria rather than ALL of the criteria, OR instead of AND if you will.
$names = Input::get('names');
$company = Input::get('company');
$contacts = Contact::where(function($query) use ($names, $tags, $type, $sector, $company)
{
if (!empty($names)) {
$query->where('firstname', 'LIKE', "%{$names}%")
->orWhere('lastname', 'LIKE', "%{$names}%");
}
if (!empty($company)) {
$query->where('company', 'LIKE', "%{$company}%");
}
})
->paginate(100);
return View::make('index')->with('contacts', $contacts)->with('searchingFlag', $searchingFlag)->with('names', $names)->with('tags', $tags)->with('type', $type)->with('sector', $sector)->with('company', $company);
So all I am doing here, I believe, is stating results must match either of the name fields AND the company field, if either is set, but as mentioned results are returned that match either of the clauses rather than both.
Can anyone help me figure out what's wrong?
Thanks
Upvotes: 0
Views: 424
Reputation: 304
if(!empty($names)) {
$query->whereRaw('firstname LIKE "%{$names}%" OR lastname LIKE "%{$names}%" ');
}
Upvotes: 1
Reputation: 81187
You need to nest wheres:
if (!empty($names)) {
$query->where(function ($q) use ($names) {
$q->where('firstname', 'LIKE', "%{$names}%")
->orWhere('lastname', 'LIKE', "%{$names}%");
}
}
This will result in:
SELECT ... WHERE (firstname like .. OR lasname like ..) AND company ...
Upvotes: 2