I am creating a class in Laravel which handles API requests with contain variables. I am then creating the Eloquent model query depending on what variables are passed to this class.
Here is my code:
class FilterVars
{
public static function filterProduct($vars, Product $product) {
$product->where('id', '=', 1);
if((array_key_exists('order_by', $vars)) && (array_key_exists('order', $vars))) {
$product->orderBy($vars['order_by'], $vars['order']);
}
return $product->get();
}
}
When I GET this url using postman :http://localhost:8931/api/v1/product?order_by=title&order=desc this returns results fine but none of my where or order_by variables are being taken into account. It returns everything regardless of what I pass in the URl.
Strangely though, when I test this piece of code, the correct results are returned:
$product->where('id', '=', 1)->orderBy($vars['order_by'], $vars['order'])->get();
It works when all the method calls are chained together. Can anyone see why my first code example would not be working?
Thanks
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire