Laravel 4.2 Eloquent Dynamic Query
I'm trying to retrieve a collection of items via my Item Model based on 8+ optional inputs.
I will have named optional inputs such as 'Item Name', 'Item Code', 'Item Colour' and would like to be able to use only the completed inputs as where clauses on my query.
I found a Laracast that I thought explained how I should be able to achieve this however I can't seem to make it work.
I had imagined that code something like:
$query = Item::select();
if(Input::has('name')) {
$query->where('ItemName', Input::get('name'));
}
if(Input::has('code')) {
....
}
$query->get();
I tested my presumptions with the following code.
If I use the following code:
$query = Item::select()->where('ItemCode', '0605')->get();
I get a collection of 5 items returned as expected but if I use the following code:
$query = Item::select();
$query->where('ItemCode', '0605')->get();
I get an Illuminate\Database\Eloquent\Builder object returned and not a collection of items as I would expect.
Can anyone see what I'm doing wrong or advise me on what the correct way to achieve this is?
Answer
Crazy thought, but just to be sure. Maybe you want this?
$query = Item::select();
if(Input::has('name')) {
$query->where('ItemName', Input::get('name'))
}
if(Input::has('code')) {
....
}
$query = $query->get();
Related Questions
- → "failed to open stream" error when executing "migrate:make"
- → October CMS Plugin Routes.php not registering
- → OctoberCMS Migrate Table
- → OctoberCMS Rain User plugin not working or redirecting
- → October CMS Custom Mail Layout
- → October CMS - How to correctly route
- → October CMS create a multi select Form field
- → October CMS - Conditionally Load a Different Page
- → How to disable assets combining on development in OctoberCMS
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → OctoberCms component: How to display all ID(items) instead of sorting only one ID?
- → In OctoberCMS how do you find the hint path?
- → How to register middlewares in OctoberCMS plugin?