nathan nathan - 5 months ago 30
SQL Question

Searching and filtering / refining database results in Laravel 4

I'm looking for a way to search and filter a database table / Eloquent model through the query string in Laravel 4.

I have a table named

houses
with the columns named:
price
,
name
,
hasCoffeeMachine
and
hasStove


I want the user to be able to do something like: http://example.com?name=test&hasCoffeeMachine=1

Which will get all the rows where the name is "test" and they have a coffee machine.

I want the user to be able to add URL parameters based on the filter they desire. What is the best way to account for all the possible combinations of query strings to return the correct results from the table?

Answer
$houses = new House;

if(Input::get('name'))
    $houses->where('name', '=', Input::get('name'));

if(Input::get('hasCoffeeMachine'))
    $houses->where('hasCoffeeMachine', '=', Input::get('hasCoffeeMachine'));

// Keep adding more for every filter you have

// Don't do this till you are done adding filters.
$houses = $houses->get();
Comments