@denis
To create a simple dynamic drop-down list in Laravel, you can follow these steps:
- Create a form in your blade template where you want to display the drop-down list.
- 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
|
- Create a controller using the artisan command:
1
|
php artisan make:controller DropdownController
|
- 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);
}
|
- 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>');
});
}
});
});
|
- Include the JavaScript file in your blade template.
1
|
<script src="{{ asset('js/dropdown.js') }}"></script>
|
- 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.