Laravel Eloquent orWhere Query
You could do in three ways. Assume you've an array in the form
['myselect' => [11, 15, 17, 19], 'otherfield' => 'test', '_token' => 'jahduwlsbw91ihp']
which could be a dump of \Input::all();
Project::where(function ($query) { foreach(\Input::get('myselect') as $select) { $query->orWhere('id', '=', $select); } })->get();
Project::whereIn('id', \Input::get('myselect'))->get();
$sql = \DB::table('projects'); foreach (\Input::get('myselect') as $select) { $sql->orWhere('id', '=', $select); } $result = $sql->get();
The best approach for this case is using Laravel's equivalent for SQL's IN()
.
Project::whereIn('id', [17, 19])->get();
Will be the same as:
SELECT * FROM projects WHERE id IN (17, 19)
This approach is nicer and also more efficient - according to the Mysql Manual, if all values are constants, IN
sorts the list and then uses a binary search.
In laravel 5 you could do it this way.
$projects = Projects::query();foreach ($selects as $select) { $projects->orWhere('id', '=', $select);}$result = $projects->get();
This is very useful specially if you have custom methods on your Projects model and you need to query from variable. You cannot pass $selects
inside the orWhere method.