Home > OS >  Laravel - ORM query with dynamic fields
Laravel - ORM query with dynamic fields

Time:07-13

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.

CodePudding user response:

You can use when() function like this:

The when method will execute the given callback when the first argument given to the method evaluates to true. The collection instance and the first argument given to the when method will be provided to the closure.

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

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

->when($marca,function($query, $marca){
    $query->where('marca',$marca);
})

->take(10)->get();

CodePudding user response:

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

CodePudding user response:

$properties = ['9','10','25'];

$products = Product::whereHas('properties', function ($q) use($properties) {
    $q->whereIn('product_property_id', $properties);

})
->orderBy('id')
->get();

I have been modifying the query to try to make it dynamic.

I have an array $properties with 3 values ​​and I would like for each of these 3 values ​​to do a "->where".

IF I do it with a whereIn, it takes those items that meet any of the conditions, but I would like it to only return those that meet all of them.

I thought I could do it with a "foreach" inside the function() but it won't let me,

$properties = ['9','10','25'];

$products = Product::whereHas('properties', function ($q) use($properties) {

    foreach ($properties as $prop) {
        $q->whereIn('product_property_id', $prop);
    }

})
->orderBy('id')
->get();
  • Related