John Davidson

php - Laravel - ORM query with dynamic fields

0 comments
Message:


I have an endpoint that can receive different fields with different names and values.
I can receive an API call in this way as in this other


endpoint.php?brand=1&car=3

endpoint.php?color=red&type=5


Since I don't know what values ​​I will receive, I want to make a query with the parameters I receive


$marca = $request->get('marca');
$calificacionEnergetica = $request->get('calificacion-energetica');

$products = Product::where('active',1)
->where('category_id',$category_id);

if ($marca !== null) {
$products = $products->where('marca',$marca);
}

if ($calificacionEnergetica !== null) {
$products = $products->where('calificacion-energetica',$calificacionEnergetica);
}

$products = $products->take(10)->get();

This is the query I have right now, but I would like to be able to tell it if you receive the parameter "brand" where('brand',$request->get('brand')


And if you also receive the parameter "color" the same for it.



My Answer:
You can achieve this by dynamically adding where clauses to your query based on the parameters you receive. Here's an example of how you can do this:

php
$filters = $request->all(); // Get all parameters

$products = Product::where('active', 1)
->where('category_id', $category_id);

foreach ($filters as $key => $value) {
if ($key !== 'category_id' && $value !== null) {
$products = $products->where($key, $value);
}
}

$products = $products->take(10)->get();


In this code snippet, we loop through all the parameters received in the request and add a where clause for each parameter (except for 'category_id' which is already handled). This way, you can dynamically filter your query based on the parameters you receive.

Rate this post

3 of 5 based on 6083 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us