javascriptlaraveljquery-select2

select2 Laravel - Always Showing JSON


I can't get the results to return to the select box, it's always showing JSON instead.

public function autocomplete(Request $request)
{
    $data = Pegawai::where('nama', 'LIKE', '%'.request('q').'%')->paginate(10);

    return response()->json($data);
}
<script>
    $(document).ready(function(){

    $("#pegawais").select2({
        placeholder:'Pilih Provinsi',
        ajax: {
            url: "{{route('autocomplete')}}",
            dataType: 'json',
            delay: 250,
            processResults: function (data) {
                return {
                    results: $.map(data, function (item) {
                        return {
                            text: item.nama,
                            id: item.id
                        }
                    })
                };
            },
            cache: true

        }
    });
});
</script>


<div class='mb-2'>
    <label> Regencies</label>
    <select id="pegawais" class="form-select" aria-label="Default select example">
    </select>
</div>

Result:

Result


Solution

  • The ->paginate() method doesn't return an array of results like you expect, it returns a LengthAwarePaginator which produces a result like this when serialized to JSON:

    {
        "current_page": 1,
        "data": [
            // Your first Pegawai,
            // Your second Pegawai
        ],
        ...
    }
    

    This part of your code is trying to call map on this whole object, rather than on the array of results (i.e. the property data):

    processResults: function (data) {
        return {
            results: $.map(data, function (item) {
                return {
                    text: item.nama,
                    id: item.id
                }
            })
        };
    },
    

    Change it to this

    processResults: function (result) {
        return {
            results: $.map(result.data, function (item) {
                return {
                    text: item.nama,
                    id: item.id
                }
            })
        };
    },