In laravel, I can write this in a resource controller to respond to get requests (let's say the resource is products):
public function index(Request $request)
{
// Handles requests such as ".../api/products?user_id=5&price=500"
$products = Product::where($request->toArray())->get();
return response($products);
}
This works fine for requests with "=", such as in the example. But what if we don't want to search for price=500, but perhaps price <= 500 or price > 500. What would be the best Laravel (and RESTful) approach for this?
Note: Laravel 5.2
You can do like this.
public function index(Request $request)
{
// Handles requests such as ".../api/products?user_id=5&price=500"
$products = Product::where('user_id', $request->user_id)->where('price', '<=', intval($request->price))->get();
return response()->json($products);
}
Or:
public function index(Request $request)
{
// Handles requests such as ".../api/products?user_id=5&price=500"
$products = Product::whereRaw("user_id=? and price<=?", [$request->user_id, $request->price])->get();
return response()->json($products);
}
Edit after @Joel Hinz comment:
If you want also to pass the operator of the query you can add a new parameter to the url, for example
/api/products?user_id=5&price=500&op=1
Then switch the number in the controller.
public function index(Request $request)
{
// Handles requests such as ".../api/products?user_id=5&price=500&op=1"
switch(intval($request->op)){
case 1:
$op = "<=";
break;
case 2:
$op = ">";
break;
//and so on
default:
return response()->json("Wrong parameters");
break;
}
$products = Product::whereRaw("user_id = ? and price $op ?", [$request->user_id, $request->price])->get();
return response()->json($products);
}