Ok, here we go. I'll try to be didactic.
TO DO
Build an API that search and returns products from database based on URL parameters.
Properties
First of all, we set an array with our all valid properties.
$props = [
'id',
'product_name',
'barcode',
'category_id',
'description',
'price'
];
Parameters
Let's store all parameters that comes from URL in a variable:
$parameters = Input::all();
Without parameters
If any parameters was passed, we can select all products with their fields and return the result:
if (empty($parameters)) {
$products = Product::all();
return $products;
}
Organizing things
Let's consider that we have 3 "categories" of parameters:
- That determines the fields to be selected (optional).
- That determines the result order (optional).
- That determines the search clauses (optional).
Identifying the fields
For the first category, we'll use the fields parameter that receives a string separating each field by commas.
$fieldsParam = $parameters['fields']; // Gets fields string.
$fieldsParamSplit = explode(',', $fieldsParam); // Split the fields string into array.
$fields = array_intersect($props, $fieldsParamSplit); // Gets only wanted fields.
The order
For the second category, we'll use the sortby parameter that receives a specific field (property) name.
$orderProp = null;
// Check if parameter "sortby" exists and if it is valid.
if (isset($parameters['sortby']) && in_array($parameters['sortby'], $props)) {
$orderProp = $parameters['sortby'];
}
There's some clause?
For the third category, we'll use all parameters (except those mentioned above) to build the where clauses of search.
$clauses = [];
foreach ($props as $prop) {
// Check if the current property is present in parameters.
if (in_array($prop, array_keys($parameters))) {
// Each item represents a where clause.
$clauses[$prop] = $parameters[$prop];
}
}
Building the collection
Now that all the paremeters are validated, we can build the collection of products and return the result.
if ($orderProp) {
$products = Product::where($clauses)->orderBy($orderProp)->get($fields);
} else {
$products = Product::where($clauses)->get($fields);
}
return $products;