php get variable value and append it to a query in a dynamic manner

Viewed 259

I am not sure how to say this, but you will get the idea from the below code. Laravel framework is used. My code is as shown below:

$keywords = ProductKeyword::orderBy('name', 'asc')->pluck('name')->toArray();
if (!empty($keywords)) {
    $str = '';
    foreach ($keywords as $key => $keyword) {
        if ($key == 0) {
            $str .= "Where('description', 'like', '%' . $keyword . '%')";                    
        } else {
            $str .= "->orWhere('description', 'like', '%' . $keyword . '%')";
        }
    }
}
$str .= "->all()";

$items = Item::$str;
dd($items);

I need the value of $str to be appended to Item model, so that in effect the php interprets this as below

$items = Item::Where('description', 'like', '%' . 'laptop' . '%')->orWhere('description', 'like', '%' . 'pc' . '%')->all();

So that I can dynamically create where-clauses.

3 Answers

You are overcomplicating things a little here. Grab the collection of keywords, and iterate those, then use orWhere() on the keywords name, and voila. Open up a query on your items with the query() method, then apply orWhere() for each iteration. Laravel will handle the rest. Once done, you just need to get() your data!

$keywords = ProductKeyword::orderBy('name', 'asc')->get();

$items = Item::query();
foreach ($keywords as $key => $keyword) {
    $items->orWhere('description', 'like', '%'.$keyword->name.'%');
}

$items = $items->get();
dd($items);

Note that if there are no keywords, it will essentially become Item::all(), since you do not apply any where-clauses.

you need to improve and fix your code:

  $query = Item::query();
  foreach ($keywords as $keyword) {
     $query->orWhere('description', 'like', '%'.$keyword.'%');
  }
  $result=$query->get();

you are using a complex way to achieve it. my answer would be almost same as @Qirel

//prepare your query
$query = Item::query();
  foreach ($keywords as $keyword) {
     //loop through the keywords in the description column of Item Table match the records which will be available in the $query
     $query->orWhere('description', 'like', '%'.$keyword.'%');
  }
  // get the records which are matched and store it in $result variable
  $result=$query->get();`enter code here`
Related