h44f33z h44f33z - 3 months ago 33x
PHP Question

Laravel 5.2 Create query using url get parameters to select fields, match string and sort

I have seen some API have simple query that can be constructed in url. For example, I have products table with Product model.

products table properties:

  • id

  • product_name

  • barcode

  • category_id

  • description

  • price

How can I do query in url as below (fields parameter means to select those specified fields):


or maybe like this to get price equalto 10.00:


I know in laravel we can check the get parameters using
and get the value using
to check and retrieve the value one by one

But I think there should be a better way to do that or maybe there is a wrapper function that can be used for all controllers to read the query from url get parameters.



Ok, here we go. I'll try to be didactic.


Build an API that search and returns products from database based on URL parameters.


First of all, we set an array with our all valid properties.

$props = [


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:

  1. That determines the fields to be selected (optional).
  2. That determines the result order (optional).
  3. 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;