
How to Create a Dropdown Dependent in Laravel 8 with jQuery AJAX

Laravel Dependent Dropdown - Hi Coders 👋 In this article, I will share about how to create dynamic dependent dropdown in laravel 8 with jQuery AJAX.
What's Dependent Dropdown ?
Dependent dropdown is a term commonly used for dropdowns or select-options that display data that depend on other dropdowns. The most common dependent dropdown example we encounter is when registering or filling out a form with country, state and city options. For example, when selecting country Indonesia, the data displayed in the dropdown or select-option state will display provincial data in Indonesia. Then if we choose the state or province of East Java, then the dropdown or select-option city will display city or district data in the state or province of East Java.
And in this tutorial, we will simulate creating a dependent dropdown to display course data in a dropdown or select-option based on parent data or course category. So just imagine, we have a simple course registration system, where when the user is going to register the course, the user needs to select the course based on the category (online or offline).
Okay, let's go straight to step by step creating dynamic dependent dropdown in laravel 8 with jQuery AJAX.👇
Laravel 8 Dynamic Dependent Dropdown
Step 1: Install Laravel
//via Laravel Installer
composer global require laravel/installer
laravel new laravel-dependent-dropdown
//via Composer
composer create-project laravel/laravel laravel-dependent-dropdown
In this first step, we need to install the latest version of laravel (currently version 8) which we will try to create or display data in dropdown or select-option based on parent data or master data (Dynamic Dependent Dropdown). To install laravel, you can use the laravel installer or use composer like the example above.
Select the method you want to use for the Laravel installation. From the two examples of laravel installation commands above, they will both generate a laravel project with the name laravel-dependent-dropdown.
Wait until the installation process is complete and when it's finished, don't forget to enter the project directory using the cd laravel-dependent-dropdown command.
Step 2: Setup Database
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_dependent_dropdown
DB_USERNAME=root
DB_PASSWORD=
Next, create a new database to store sample data that we will use in this experiment, namely category and course data. If you are using xampp as local development, please create a new database at localhost/phpmyadmin. Here I give an example, I created a new database with the name laravel_dependent_dropdown. Then don't forget to also adjust the DB_DATABASE in the .env file as in the example above.
Step 3: Create Model & Migration
Then we will create two new model & migration files namely Category and Course.
php artisan make:model Category -m
First, we create the model and migration files for the category. Run artisan command as above to generate model file and migration category
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->timestamps();
});
}
After successfully generating the model file and migration category, now open the category migration file located in database/migrations/xxxx_xx_xx_xxxxxx_create_categories_table.php. Then in the function up, add a string name like the code above.
php artisan make:model Course -m
For the second, we need to generate model and migration files for the course. For that, run the artisan command as above to generate the course model and migration files.
public function up()
{
Schema::create('courses', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->integer('category_id');
$table->timestamps();
});
}
Then, open the course migration file that was just generated and located in database/migrations/xxxx_xx_xx_xxxxx_create_courses_table.php. In the function up, add a string name and an integer category_id like the code above.
php artisan migrate
If you have generated two model and migration files for the category and course and have setup the two migration files, continue by running the php artisan migrate command to migrate all migration files to the database.
Step 4: Create Seeder
OK. We have created two tables, namely categories and courses, now we will insert data into both tables using seeders.
php artisan make:seeder CategorySeeder
First, we need to create a seeder file for the category. Run the artisan command as above to create a CategorySeeder file.
public function run()
{
\DB::table('categories')->insert([
['name' => 'online'],
['name' => 'offline']
]);
}
Then, open the CategorySeeder file that has been generated and change the run method to be like the code above.
php artisan make:seeder CourseSeeder
Next, we create a CourseSeeder file with the command as above.
public function run()
{
\DB::table('courses')->insert([
[
'name' => 'Laravel Master Class',
'category_id' => 1
],
[
'name' => 'Laravel for Beginners',
'category_id' => 1
],
[
'name' => 'CodeIgniter 4: Build a Complete Web Application from Scratch',
'category_id' => 1
],
[
'name' => 'The Modern JavaScript Bootcamp',
'category_id' => 2
],
[
'name' => 'JavaScript: The Advanced Concepts (2021)',
'category_id' => 2
],
[
'name' => 'Learning Alpine.JS',
'category_id' => 2
],
[
'name' => 'Start with TALL: Use Tailwind, Alpine, Laravel & Livewire',
'category_id' => 2
],
]);
}
If you have successfully generated or created the CourseSeeder file, now open the file and change the run method to be like the code above. Here, we will insert some course data with different category_id into the courses table.
public function run()
{
$this->call([
CategorySeeder::class,
CourseSeeder::class
]);
}
Next, open the DatabaseSeeder.php file and in the run method, call the CategorySeeder and CourseSeeder classes as above.
php artisan db:seed
To run or insert category and course data into the database based on the Seeder file that we have created and setup, we need to run the php artisan db:seed command.
Step 5: Setup Route
Route::get('/', function () {
$category = App\Models\Category::all();
return view('welcome',['category' => $category]);
});
Route::get('getCourse/{id}', function ($id) {
$course = App\Models\Course::where('category_id',$id)->get();
return response()->json($course);
});
Okay. In this fifth step, we will setup a route by updating the default route from laravel and adding a new route to retrieve or display course data based on the selected data category.
So, please open the routes/web.php file and adjust the existing code to be like the code above.
Step 6: Setup View
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-F3w7mX95PdgyTmZZMECAngseQB83DfGTowi0iMjiWaeVhAn4FJkqJByhZMI3AhiU" crossorigin="anonymous">
<title>Laravel 8: Dynamic Dependent Dropdown</title>
</head>
<body>
<div class="container my-5">
<h1 class="fs-5 fw-bold my-4 text-center">How to Create Dependent Dropdown in Laravel</h1>
<div class="row">
<form action="">
<div class="mb-3">
<label for="category" class="form-label">Category</label>
<select class="form-control" name="" id="category">
<option hidden>Choose Category</option>
@foreach ($category as $item)
<option value="{{ $item->id }}">{{ $item->name }}</option>
@endforeach
</select>
</div>
<div class="mb-3">
<label for="course" class="form-label">Course</label>
<select class="form-control" name="course" id="course"></select>
</div>
</form>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-/bQdsTh/da6pkI1MST/rWKFNjaCP5gBSY4sEBT38Q/9RBh9AH40zEOg7Hlq2THRZ" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script>
$(document).ready(function() {
$('#category').on('change', function() {
var categoryID = $(this).val();
if(categoryID) {
$.ajax({
url: '/getCourse/'+categoryID,
type: "GET",
data : {"_token":"{{ csrf_token() }}"},
dataType: "json",
success:function(data)
{
if(data){
$('#course').empty();
$('#course').append('<option hidden>Choose Course</option>');
$.each(data, function(key, course){
$('select[name="course"]').append('<option value="'+ key +'">' + course.name+ '</option>');
});
}else{
$('#course').empty();
}
}
});
}else{
$('#course').empty();
}
});
});
</script>
</body>
</html>
The last step, we will change all the code in the default resources/views/welcome.blade.php file from laravel to be like the code above. In this welcome.blade.php file, we are using the starter template from bootstrap 5 and additionally using jQuery.
Then we add two dropdowns or select-options to display category and course data. In addition, we also use jQuery AJAX to be able to display course data in a dropdown or select-option dynamically based on the selected category.
With the jQuery AJAX script, for example, when the user selects an online category (id 1), the category id (1) will be thrown into the getCourse route which is then used as a parameter to retrieve or display course data that has a category_id value of 1 (or online) and data it will be displayed in the dropdown or select-option course.
Step 7: Testing
Until the end of this tutorial article, we can do testing to display data in a dropdown or select options based on the parent (Dynamic Dependent Dropdown). To test it, please run the laravel project first with the php artisan serve command, then try opening the laravel project in the browser.
First, we try to select one category, then the data in the dropdown or select-option course will display course data that has the same category_id value as the category you selected earlier.
Enough of this article that discusses how to create dynamic dependent dropdowns in laravel 8 with jQuery AJAX. Hopefully this article can be useful and see you in the next article. 👋
- Cara Mengatasi Error XAMPP: MySQL shutdown unexpectedly 23 Oktober 2021 67047 views
- Laravel 8: REST API Authentication dengan Sanctum 17 September 2021 32220 views
- Tutorial CRUD (Create, Read, Update & Delete) Codeigniter 4 dengan Bootstrap 14 Oktober 2021 31779 views
- Membuat REST API CRUD di Laravel 8 dengan Sanctum 18 September 2021 28528 views
- Contoh Cara Menggunakan Sweet Alert di Laravel 8 27 Agustus 2021 27860 views