Retrieve the value of a PHP variable and dynamically add it to a query

There is a way to achieve this using the Laravel framework. Below is a snippet of code that demonstrates how to dynamically create where clauses:

$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);

In order for the value of $str to be appended to the Item model, you can modify the code as follows:

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

This will provide you with the ability to dynamically create where-clauses in your application.

Answer №1

Don't overthink it too much. Simply gather all the keywords, loop through them, and use orWhere() on the keyword name. That's it! Start by creating a query for your items using the query() method, then add orWhere() inside a loop for each keyword. Laravel will take care of everything else. Finally, just call get() to retrieve 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);

Keep in mind that if there are no keywords, the code will essentially be equivalent to Item::all(), as no where-clauses are applied.

Answer №2

It's essential to enhance and rectify your code:

  $searchQuery = Product::query();
  foreach ($searchKeywords as $word) {
     $searchQuery->orWhere('product_name', 'like', '%'.$word.'%');
  }
  $finalResult=$searchQuery->get();

Answer №3

You're taking a more intricate approach to solve this problem. My solution is very similar to what @Qirel suggested

//set up your query
$query = Item::query();
foreach ($keywords as $keyword) {
   //loop through the keywords in the description column of the Item Table to find matching records and add them to the $query
   $query->orWhere('description', 'like', '%'.$keyword.'%');
}
// retrieve the matched records and store them in the $result variable
$result=$query->get();`enter code here`

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using PHP to send post requests with Ajax for DataTables functionality

I'm currently working on populating a datatable using datatables.net. There's a specific field that triggers an AJAX post request after it's changed. Here is the JavaScript code: jQuery(document).ready(function() { if(window.location.h ...

Using a combination of PHP and JQuery, I noticed that adding an IF statement within the document ready function

In the (document).ready function, the code below is used to properly display the order form: <?php if (isset($_POST['preview-order'])) { //IF PREVIEW FORM ?> $("#cam-order-preview").show('slow'); <?ph ...

Leveraging Postmark in PHP applications

Hey there, I'm currently diving into the world of PHP and Postmark in an effort to set up a form submission that sends data to my email. While I've managed to get the email functionality working, I'm encountering an issue with redirecting to ...

Validation in bootstrap forms is not functioning properly

I am facing an issue with my bootstrap modal. I have a form in temp.php file loaded into myModal, and when I try to submit it to save.php using AJAX, the form validation does not work as expected (it does not check if it is empty before submission). Howeve ...

What is the best way to incorporate multiple conditions within a single foreach loop?

Is it possible to have multiple conditions in a single foreach loop like this: "foreach($products as $product && $categories as $category)"? If not, what would be the correct way to proceed? ...

Complete the form to redirect to a new webpage

I'm facing an issue here, wondering how I can submit a form on one URL and another form on a different URL simultaneously... For example: form1.php: <form> <input type="text" name="name" id="name"> <input type="submit" href ...

PHP query will execute even in the absence of clicking the button

I'm encountering an unusual issue. I've defined a query to insert two names into the database, and I've used Javascript(Jquery) to ensure it only runs when the create button is clicked. However, the script seems to be executing every time I ...

Stop jQuery from adding duplicate values to a table

When I make an AJAX call using jQuery and PHP to receive JSON response, I am encountering a problem with duplicate values. The code is functioning correctly, but when selecting an option from the drop-down list, duplicate entries appear. The scenario invol ...

Share a URL and display small previews from it - php

Have you ever noticed that on certain websites, such as Facebook, when you post a link it automatically displays thumbnails from the linked website? Like in the image below: Ever wondered how to achieve that effect? ...

Making changes to a JSON File

I've been attempting to integrate a jQuery gantt chart into my WordPress website as a plugin. However, I've hit a roadblock when it comes to editing the data.json file. My approach involves using a PHP form to add a new item. Upon form submission ...

The chosen option from the drop-down menu cannot be shown on the screen

I have developed an application that you can access for testing purposes APPLICATION, but I am encountering some minor issues that I'm struggling to resolve. Despite having correct queries, the selected module is not being displayed in the code sn ...

manipulating session variables with javascript ajax and php

I'm struggling with setting and retrieving session variables using JavaScript code that calls PHP functions via AJAX. I want to access the returned session field in my JavaScript, but nothing seems to be working. Can someone take a look at my code and ...

WordPress Custom PDF Loading Script: PDF document failed to load

Looking for Assistance: I am in need of a PHP script that can retrieve and load PDF files from a specific directory. For instance, when I visit the URL www.mydomainameweb.com/wp-content/themes/elegant/pdf.php?file=a.pdf (or www.mydomainameweb.com/pdf?file= ...

Monitor changes in the select tag to display the updated value and output

I am new to using jQuery. While I have practiced using native PHP Ajax in the past, I now recognize the need to learn jQuery due to current technological advancements and demands. When the select tag changes, I send the "types" value via POST method to a ...

Encountered an issue while attempting to make a GET request from nodejs to apache

Utilizing Node.js to send a request to an Apache server under certain conditions and then executing a PHP function related to that request. Node.js GET Request (server.js) var options = { host: 'localhost', port: 80, ...

How can I calculate the total number of days between the from_date and to_date using PHP in CodeIgniter?

$from_date = $this->input->post('from_date');12/3/2016 $to_date = $this->input->post('to_date');14/3/2016 I am looking for a solution that will provide me with the total number of days between two dates. For example, consid ...

SQL Alert: The table or view has already been created

I am encountering an error while trying to create a table in MySQL. The specific error message I receive is as follows: SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'migrations' already exists (SQL: create table migrations (i ...

What techniques can I utilize to trim down this SQL query?

SELECT lesson_id_1, lesson_id_2, lesson_id_3, lesson_id_4, lesson_id_5, lesson_id_6, lesson_id_7, lesson_id_8, lesson_id_9, lesson_id_10 FROM hub_attendance WHERE student_id='351' AND ...

Utilizing jQuery autocomplete in an onKeyup event handler

Looking for a way to display the results of a jQuery function. As the user types in the search field, a function is triggered which retrieves data from the database. I can view the retrieved data using an alert function. <input type="text" n ...

Oh no, Symfony 2.6 is throwing a Doctrine ORMException: The EntityManager has been shut down

Currently, I am in the process of importing users from an excel file. To manage this task effectively, I have established an entity manager: $em = $this->getDoctrine()->getManager(); Here is a snippet of the loop I am using for this operation: .. ...