vendredi 17 février 2017

Formatting JSON response in Laravel 5 for Select2.js

I am populating a city list (after selecting a county from a dropdown), using an Ajax call with Laravel 5.2 and Select2.js.

I want to format the JSON response from the ajax call so it matches the Select2 criterias for displaying on a dropdown list (id,text)

Here is my controller:

public function postCounty(Request $request)
{
    if($request->ajax()) 
    {
        $county = County::findOrFail($request->input('county_id'));
        $cities = $county->cities()->orderBy('title', 'ASC')->get();
        return response()->json($cities);
    }
}

It works fine and return a list of cities:

[
    {"id":1,"title":"City 1","slug":"city-1"},
    {"id":2,"title":"City 2","slug":"city-2"},
    {"id":3,"title":"City 3","slug":"city-3"}
]

I need to retrieve only the columns id and title, so I use ->pluck('title', 'id')

It returns this:

{"1":"City 1","2":"City 2","3":"City 3"}

To display the results correctly on my select options list, using Select2, I need the results to return like this:

[
    {"id":"1","text":"City 1"},
    {"id":"2","text":"City 2"},
    {"id":"3","text":"City 3"}
]

I know that I can format the results from the ->get() array, using JavaScript and the Select2 processResults, but I want to do it using the controller so it formats the JSON response directly.

Here is a simplified version of my JS:

$("#countyFilter").select2().on("select2:selecting", function(e) {
    var county_id = $(this).val();
    $.ajax({
        type:'GET',
        url: 'http://ift.tt/2m1PXd8',
        data: {county_id:county_id},
        success: function(data){
            $("#populateCities").select2({
                data:data
            });
        }
    });
});

That script works almost fine, only the data needs to be formatted.

My question:

How to format the JSON response in the controller so it returns [{"id":1,"text":"City 1"}] instead of [{"id":1,"title":"City 1","slug":"city-1"}]



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2kwLEu9
via IFTTT

Aucun commentaire:

Enregistrer un commentaire