Friend Friend - 6 months ago 29
PHP Question

Laravel Query Builder: where condition based on user input

Here is my output of

print_r($_POST)


array([id] => '123', [name] => '', [place] => '', [color] => '')


Where
name
,
place
and
color
are optional fields submitted by user..... user may select only
name
,
place
or
color
,
name + color
,
color + place
, or all three
name + color + place
.

How can I put
where
condition for these options chosen by user? Let's say for example, In Laravel we select DB table using the following statement...

$Select_db = Db::table('mytable')
->where('name', Input::get('name'))
->where('place', Input::get('place'))
->where('color', Input::get('color'))
->select()
->get();


As you can see above condition works only if there is an input for all fields from user, based on user input I want add
where
condition, how do we fix this???

Note: In this particular scenario, I am aware I could use
isset()
for each condition. However, what if there are many optional inputs?

DWX DWX
Answer

Try this:-

$query = DB::table('mytable');

if (Input::get('name') != "")
    $Select_db->where('name', Input::get('name'));

if (Input::get('place') != "")
    $Select_db->where('place', Input::get('place'));

if (Input::get('color') != "")
    $Select_db->where('color', Input::get('color'));

$result = $Select_db->get();

And if there are multiple columns to match, then try using this:-

$Select_db = DB::table('mytable'); 
foreach($_POST as $key => $val){
    if(Input::get($key) != ""){
        $Select_db->where($key, Input::get($key));
    }   
} 
$Select_db->get();
Comments