Laravel - ORM query with dynamic fields

304 Views Asked by At

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.

1

There are 1 best solutions below

0
Chintan Mathukiya On

If you have dynamic param then you need to get all the param and set where condition for each by foreach loop. I have set it. It may help to you.

$inputs = $request->query(); // Hear you can use Request::all(); if you want all GET and POST both param

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

foreach ($inputs as $key=>$value) {
    if ($value !== null) {
        $products->where($key,$value);
    }
}

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