ajsmith_codes
1 month ago
223
3
Laravel

Polymorphic relationship returns object.

Posted 1 month ago by ajsmith_codes

Using Laravel 7.

I make an api call to obtain a list of contacts when a user chooses a customer. The response is returned via json_encode.

For some reason, I keep getting an object, which is not working with my custom javascript. Maybe someone can see what I'm doing wrong?

Here is the JS Code:

$('select[name="customer_id"]').on('change', function () {

    var customerId = $(this).val();

    if (customerId) {
        $.ajax({
            url: '/api/customer/contacts/get/' + customerId,
            type: "GET",
            dataType: "json",
            beforeSend: function () {
                $('#loader').css("visibility", "visible");
            },

            success: function (data) {

                $('input[name="email"]').val('');

                $('select[name="contact_id"]').empty();

                $('select[name="contact_id"]').append('<option value="Choose">Choose Contact</option>');

                $.each(data, function (key, value) {

                    $('select[name="contact_id"]').append('<option value="' + key + '">' + value + '</option>');

                });
            },
            complete: function () {
                $('#loader').css("visibility", "hidden");
            }
        });
    } else {
        $('select[name="customer_id"]').empty();
    }

});

Here is the controller:

    $customer = Customer::where('id', $id)->first();

    $contacts = $customer->contacts;


    return json_encode($contacts);

And here is the form select:

                        <select
                            name="contact_id"
                            class="shadow text-sm text-center"
                        >
                            @if(old('contact_id'))
                                @foreach($contacts as $contact)

                                    <option
                                        value="{{ old('contact_id') }}"
                                        {{ $contact->id == old('contact_id') ? 'selected' : ''}}>
                                        {{ $contact->name }}
                                    </option>

                                @endforeach

                            @else

                                <option>

                                </option>

                            @endif

                        </select>

Please sign in or create an account to participate in this conversation.