Wypełnianie selecta danymi z kontrolera

0

mam sobie taką metodę, którą wołam ajaxem

    public function findLocation($customerId)
    {
        $locations = Location::where('customer_id', $customerId)->pluck('id', 'location_name');

        return $locations->toJson();
    }

to mi daje taki output
{"LOK_01":2,"LOK_066":3}

teraz JS

        $( '#customer_id' ).on('change', function(e){

            var id  = $( this ).val();
            var url = '/document/post/' + id;

            $.get(url, function (data) {
                $( '#location_id' ).select2( 'destroy' );
                $( '#location_id' ).find( 'option' ).remove();

                $( '#location_id' ).select2({
                   data: data
                });
                console.log(data);
            });
        });

rezultat jest taki, że owszem wypełniam select2 opcjami ale każdy znak z {"LOK_01":2,"LOK_066":3} jest w osobnej opcji. Generalnie źle wypełniam select2.

0

spróbuj tak - select2 chce JSONa z id i text

    public function findLocation($customerId)
    {
        $locations = Location::where('customer_id', $customerId)->get();

        $formatted_tags = [];

        foreach ($locations as $location)
        {
            $formatted_tags[] = ['id' => $location->id, 'text' => $location->location_name];
        }

        return response()->json($formatted_tags);
        
    }

a w js spróbuj tak

        $( '#customer_id' ).on('change', function(e){

            var id  = $( this ).val();
            var url = '/document/post/' + id;

            $.ajax({

                type: "get",
                url: url,
                dataType: 'json',
                success: function (data) {
                    $( '#location_id' ).find( 'option' ).remove();
                    $( '#location_id' ).select2({
                        data: data
                    });
                }
            })
        });

dostosuj do siebie bo na czuja...

1 użytkowników online, w tym zalogowanych: 0, gości: 1