How to make simple dynamic drop list in laravel?

Member

by denis , in category: PHP Frameworks , 3 months ago

How to make simple dynamic drop list in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by edmond_brakus , 2 months ago

@denis 

To create a simple dynamic drop-down list in Laravel, you can follow these steps:

  1. Create a form in your blade template where you want to display the drop-down list.
  2. Define a route in your web.php file to handle the AJAX request that will populate the drop-down list dynamically.
1
Route::get('/getdata', 'DropdownController@getData'); // define the route for AJAX request


  1. Create a controller using the artisan command:
1
php artisan make:controller DropdownController


  1. In the DropdownController, create a method to fetch the data that will be used to populate the drop-down list dynamically.
1
2
3
4
5
public function getData()
{
    $data = //your data fetching logic here
    return response()->json($data);
}


  1. Create a JavaScript file that will make an AJAX request to fetch data from the controller method.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
$(document).ready(function() {
    $.ajax({
        url: '/getdata',
        type: 'GET',
        success: function(response) {
            var dropdown = $('#dropdown-list');
            dropdown.empty();
            $.each(response, function(index, value) {
                dropdown.append('<option value="' + value.id + '">' + value.name + '</option>');
            });
        }
    });
});


  1. Include the JavaScript file in your blade template.
1
<script src="{{ asset('js/dropdown.js') }}"></script>


  1. Finally, create the drop-down list in your blade template.
1
2
3
<select id="dropdown-list">
    <option value="">Select option</option>
</select>


Now, when the page is loaded, the JavaScript file will make an AJAX request to fetch data from the controller method and populate the drop-down list dynamically.