title: Formatting JSON response in Laravel 5 for Select2.js
body: <p>I am populating a city list (after selecting a county from a dropdown), using an Ajax call with Laravel 5.2 and Select2.js.</p>
  
  <p>I want to format the JSON response from the ajax call so it matches the Select2 criterias for displaying on a dropdown list (<code>id</code>,<code>text</code>)</p>
  
  <p>Here is my controller:</p>
  
  <pre><code>public function postCounty(Request $request)
  {
      if($request-&gt;ajax()) 
      {
          $county = County::findOrFail($request-&gt;input('county_id'));
          $cities = $county-&gt;cities()-&gt;orderBy('title', 'ASC')-&gt;get();
          return response()-&gt;json($cities);
      }
  }
  </code></pre>
  
  <p>It works fine and return a list of cities:</p>
  
  <pre><code>[
      {"id":1,"title":"City 1","slug":"city-1"},
      {"id":2,"title":"City 2","slug":"city-2"},
      {"id":3,"title":"City 3","slug":"city-3"}
  ]
  </code></pre>
  
  <p>I need to retrieve only the columns <code>id</code> and <code>title</code>, so I use <code>-&gt;pluck('title', 'id')</code></p>
  
  <p>It returns this:</p>
  
  <pre><code>{"1":"City 1","2":"City 2","3":"City 3"}
  </code></pre>
  
  <p>To display the results correctly on my select options list, using Select2, I need the results to return like this:</p>
  
  <pre><code>[
      {"id":"1","text":"City 1"},
      {"id":"2","text":"City 2"},
      {"id":"3","text":"City 3"}
  ]
  </code></pre>
  
  <p>I know that I can format the results from the <code>-&gt;get()</code> array, using JavaScript and the Select2 <code>processResults</code>, but I want to do it using the controller so it formats the JSON response directly.</p>
  
  <p>Here is a simplified version of my JS:</p>
  
  <pre><code>$("#countyFilter").select2().on("select2:selecting", function(e) {
      var county_id = $(this).val();
      $.ajax({
          type:'GET',
          url: 'mysite.com/api/county',
          data: {county_id:county_id},
          success: function(data){
              $("#populateCities").select2({
                  data:data
              });
          }
      });
  });
  </code></pre>
  
  <p>That script works almost fine, only the <code>data</code> needs to be formatted.</p>
  
  <p><strong>My question:</strong> </p>
  
  <p>How to format the JSON response in the controller so it returns <code>[{"id":1,"text":"City 1"}]</code> instead of <code>[{"id":1,"title":"City 1","slug":"city-1"}]</code></p>