Ad

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?

Ad

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();
Ad
source: stackoverflow.com
Ad