Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

skiab0x's avatar

Is it possible to populate a select drop-down menu from an external api?

Hello guys. I am wondering if it is possible to populate a select drop-down menu in a blade template using an external api. I googled this question and all the answers are examples that use a database for the select drop-down menu filling with data. Thank you!

0 likes
12 replies
Snapey's avatar

sure. I would create a class that does the API calling and then use it in the controller and send its output to the view.

If the API takes some time then you might want to consider caching the results.

skiab0x's avatar

Do you believe that I should go like this, I mean with Laravel custom helper classes or should I use jquery directly on the page?

skiab0x's avatar

@sinnbeck Is is easy for select2 library to communicate with a blade template select at the same page?

Sinnbeck's avatar

The markdown is just simple html which works great in laravel/blade

<select class="js-data-example-ajax"></select>
Sinnbeck's avatar

Or any other classname. Or an ID. Check the link I posted. You are just using the class/id to tell jquery which element to activate select2 on. Have you used jquery before?

skiab0x's avatar

@sinnbeck I tried to use this example code in your link but it doesn't seem to work. Here is the code

<div class="form-row">
                                <div class="form-group col-md-6 col-lg-3">
                                    <label>ShortCode</label>
                                    <select class="form-control" name="shortcode" id="formControlSelectShortCode" required>

                                    </select>
                                </div>
                            </div>
<script>

        // Put your script here (that is only necessary for this page)!
        $('formControlSelectShortCode').select2({
            ajax: {
                url: 'https://api.github.com/search/repositories',
                dataType: 'json'
                // Additional AJAX parameters go here; see the end of this chapter for the full code of this example
            }
        });

    </script>
MichalOravec's avatar

@skiab0x You miss there id selector #

 $('#formControlSelectShortCode').select2({
    ajax: {
        url: 'https://api.github.com/search/repositories',
        dataType: 'json'
    }
});
Sinnbeck's avatar

You are missing a #. It tells jquery to use the id. A dot (.) means class

$('#formControlSelectShortCode').select2

Please or to participate in this conversation.