0

I am new to Laravel,

the query string from url may be three kind

  1. Both "Filter" and "Status": http://localhost/products?filter=productName&value=Test+Product+1&status=A&action=Filter+Result
  2. "Filter" only and "Status" will be empty: http://localhost/products?filter=productName&value=Test+Product+1&status=&action=Filter+Result
  3. "Status only and "Filter" will be empty: "Filter" and "Status" http://localhost/products?filter=&value=&status=A&action=Filter+Result

Now from Controller i can access the Query string with $inputQ = Request::input()

in normal php i can do easy like below

$sql = 'SELECT * FROM products WHERE 1 = 1';

if(isset($_REQUEST['filter']) && $_REQUEST['filter'] != '' && $_REQUEST['value'] != ''){
$sql .= 'AND `'.$_REQUEST['filter'].'` = "'.addslashes($_REQUEST['value']).'"';
}

if(isset($_REQUEST['status']) && $_REQUEST['status'] != ''){
$sql .= 'AND `status` = "'.addslashes($_REQUEST['status']).'"';
}

$res = mysql_query($sql);

Now i need to build Laravel Eloquent please help me.

2
  • laravel.com/docs/4.2/queries#advanced-wheres Commented Feb 17, 2015 at 9:23
  • @nbin i have read that... my question is i need to add WHERE only when the particular parameter found in URL and if the parameter value is not empty. can you give me some sample code? Commented Feb 17, 2015 at 9:32

1 Answer 1

1

I think you're looking for something like this? I didn't test it but i guess it should work.

$query = DB::table('products')->where(1, '=', 1);

if(Input::has('filter') && Input::has('value')){
    $query->where(Input::get('filter'), '=', Input::get('value'));
}

if(Input::has('status')){
    $query->where('status', '=', Input::get('status'));
}

$res = $query->get();
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the code, i have Model called ProductModel if i use $query = ProductModel::where(1, '=', 1); like this it wont works why?
Does this code work ? i just translated your original code to laravel query. laravel.com/docs/4.2/queries. ProductModel::where(...) will not work as it will always return an array of objects or an object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.