title: Laravel API : how to get only some fields and sort the response
body: <p>I would like to know if I do the things correctly.</p>
  <p>Let's say I have a table &quot;countries&quot;. To get only some fields of this table, in a certain order, I have this url :</p>
  <p><code>/countries?fields=id,country_name&amp;desc=country_name</code></p>
  <p>And the result is clear:</p>
  
  <pre class="lang-php prettyprint-override"><code>[
      {
          &quot;id&quot;: &quot;SP&quot;,
          &quot;country_name&quot;: &quot;Spain&quot;
      },
      {
          &quot;id&quot;: &quot;IT&quot;,
          &quot;country_name&quot;: &quot;Italy&quot;
      },
      {
          &quot;id&quot;: &quot;FR&quot;,
          &quot;country_name&quot;: &quot;France&quot;
      },
      {
          &quot;id&quot;: &quot;CN&quot;,
          &quot;country_name&quot;: &quot;China&quot;
      } ]
  </code></pre>
  <p>To do that I have this route :</p>
  <pre class="lang-php prettyprint-override"><code>Route::get('/countries', 'CountryController@index');
  </code></pre>
  <p>And the method index is :</p>
  <pre class="lang-php prettyprint-override"><code>public function index(Request $request)
  {
     
      $query = Country::query();
     
      if ($request-&gt;has('fields')){         
          $fields = explode(',', $request-&gt;input('fields') );          
          foreach ($fields as $field) {
              $query-&gt;addSelect($field);
          }        
      }
      
      if ($request-&gt;has('sort')){
          $query-&gt;orderBy($request-&gt;input('sort'));
      }
      
      if ($request-&gt;has('desc')){
          $query-&gt;orderBy($request-&gt;input('desc'), 'desc');
      }
     
      $countries = $query-&gt;get();
      
      return response()-&gt;json($countries, 200);
  }
  </code></pre>
  <p>It works fine.</p>
  <p>My question is am I doing the things correctly ? Is there any other methods ?</p>