laravel - php get variable value and append it to a query in a dynamic manner
Get the solution ↓↓↓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 toItem
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.
Answer
Solution:
You are overcomplicating things a little here. Grab the collection of keywords, and iterate those, then useorWhere()
on the keywords name, and voila. Open up a query on your items with thequery()
method, then applyorWhere()
for each iteration. Laravel will handle the rest. Once done, you just need toget()
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 becomeItem::all()
, since you do not apply any where-clauses.
Answer
Solution:
you need to improve and fix your code:
$query = Item::query();
foreach ($keywords as $keyword) {
$query->orWhere('description', 'like', '%'.$keyword.'%');
}
$result=$query->get();
Answer
Solution:
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`
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: filter_sanitize_string
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.