title: How can I take a big amount of GET parameters and filter a query depending on them cleanly?
body: <p>I have this controller for a RESTful API I am building in Laravel Lumen which takes a relatively big amount of parameters and parses them into where queries, and data is fetched depending on if they were provided. For example, </p>
  
  <pre><code>GET /nodes?region=California
  GET /nodes?ip=127.0.0.1
  </code></pre>
  
  <p>I am currently taking them in the constructor, building an array of the parameters (since I couldn't figure out how to get the raw get array in Lumen and it would be inconvenient because I already have other parameters there), and filtering out the null values (I am setting values to null if they are not in the query).</p>
  
  <p>Now, when it comes to filtering the values each in the array, I am doing it by a foreach array. This is the cleanest way I could figure out to do it, without too much code (I don't want to make my controllers too fat.).
  Is there any other way to do this cleanly, maybe with separation of functions/classes?</p>
  
  <p>Here is my constructor code:</p>
  
  <pre><code>/**
   * Get some values before using functions.
   * 
   * @param Request $request Instance of request.
   */
  public function __construct(Request $request)
  {
      $this-&gt;offset = (int) $request-&gt;input('offset', 0);
  
      // TODO: I'm not sure how to implement this, code in question
      $this-&gt;filters = [
          'region' =&gt; $request-&gt;input('region', null),
          'name' =&gt; $request-&gt;input('name', null),
          'ip' =&gt; $request-&gt;input('ip', null)
      ];
  
      $this-&gt;filters = array_filter($this-&gt;filters, function ($v) {
          return !is_null($v);
      });
  
      // Set a sane SQL limit.
      $this-&gt;limit = 5;
      $this-&gt;request = $request;
  }
  </code></pre>
  
  <p>And the controller code:</p>
  
  <pre><code>/**
   * List all nodes.
   * 
   * @return [string] [JSON containing list of nodes, if sorted.]
   */
  public function all()
  {
      try {
          // use filters provided
          $data =  Nodes::limit($this-&gt;limit)-&gt;offset($this-&gt;offset);
  
          foreach ($this-&gt;filters as $filter =&gt; $value) {
              $data-&gt;where($filter, $value);
          }
  
          $data = $data-&gt;get();
          $response = $this-&gt;respond($data);
      } catch (\Exception $e) {
          $response = $this-&gt;respondServerError('Could not retrieve data from database.');
      }
  
      return $response;    
  }
  </code></pre>