0

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.

radgezito
  • 13
  • 3
  • What have you tried? You can loop over `$request->input()`, or `$request->only(['array', 'of', 'allowed', 'columns'])` and use the key/value to construct `where()` clauses, etc. We can help you, but it's as Stackoverflow is not a free coding service, you're still expected to make an effort to solve you own problem, and include any code and errors you've written or are encountering. – Tim Lewis Jul 12 '22 at 15:12
  • Thanks, I've tried several things none without success. The one that you comment is not valid because I do not know the parameters that I will receive, I can receive 1..2 or 10 – radgezito Jul 12 '22 at 15:21
  • A `foreach` will handle 0-∞ parameters though; you just need to validate them. I.e. if I do `?bogus=meh`, then `foreach($request->input() as $key => $value) { $query->where($key, $value); }` would trigger an error, as there is no `bogus` column in your table. – Tim Lewis Jul 12 '22 at 15:22
  • But if you did `foreach($request->only(['color', 'brand', 'car', type']) as $key => $value)`, it would work, and ignore them if they are not in that list, or not provided. You'd have to do some logic to construct that array of accepted values, but that solution should work, unless I'm missing something. – Tim Lewis Jul 12 '22 at 15:24

1 Answers1

0

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