title: Laravel 5.6 Api - Search,sort and filter on list of data
body: <p>Hi I am developing a rest api endpoint for retrieving paginated list of users. In the frontend, there are options to search with all the listed columns, sort by all columns and filter by name, status and created date.</p>
  
  <p>So far I have created a repository and local scopes in user model for search, sort and filter. This is my code so far. I am confused with the filter option. Since a user a call filter with all the three options. How to pass those values in api in most optimised way?</p>
  
  <p><strong>Controller:</strong></p>
  
  <pre><code>public function index(Request $request)
  {
      $this-&gt;userRepository-&gt;getAllUsers($request);
  }
  </code></pre>
  
  <p><strong>Repository function:</strong></p>
  
  <pre><code>public function getAllUsers($request)
  {
      // Search Parameter
      isset($request-&gt;q)? $q = $request-&gt;q: $q = null;
  
      // Sort Parameter
      if ( isset($request-&gt;sortby) &amp;&amp; (isset($request-&gt;direction)) ) {
          $sort[$request-&gt;sortby] = $request-&gt; direction;
      }
  
      return User::where('type','=','student')
                  -&gt;ofSearch($q)
                  -&gt;ofSort($sort)
                  -&gt;paginate($per_page)
  }
  </code></pre>
  
  <p><strong>Model:</strong></p>
  
  <pre><code>public function scopeOfSearch($query, $q)
  {
      if ( $q ) {
          $query-&gt;orWhere('name', 'LIKE', '%' . $q . '%')
                -&gt;orWhere('school', 'LIKE', '%' . $q . '%')
                -&gt;orWhere('email', 'LIKE', '%' . $q . '%')
                -&gt;orWhere('phone', 'LIKE', '%' . $q . '%')
                -&gt;orWhere('class', 'LIKE', '%' . $q . '%');
      }
  
      return $query;
  }
  
  public function scopeOfSort($query, $sort = [])
  {
      if ( ! empty($sort) ) {
          foreach ( $sort as $column =&gt; $direction ) {
              $query-&gt;orderBy($column, $direction);
          }
      } 
      else {
          $query-&gt;orderBy('users.name'); 
      }
  
      return $query;
  }
  </code></pre>