Code your dreams into reality.
Every line of code is a step towards a better future.
Embrace the bugs, they make you a better debugger.

Laravel 11 Dynamic Dependent Dropdown using Ajax Tutorial

Last Updated on May 7, 2024 by

Dynamic categories and subcategories dependent dropdown helps users to select categories on dropdown and populate data in subcategory dropdown based on categories selection using jquery ajax.

Let’s start creating categories and subcategories select dropdown using jQuery AJAX:

Step 1: Define Routes

Define routes in routes/web.php for handle category and subcategory options data requests via ajax:

use App\Http\Controllers\CategoryController;

Route::get('/category', function () {
    return view('category');
});

Route::get('categories', [CategoryController::class, 'getCategories']);
Route::get('subcategories/{id}', [CategoryController::class, 'getSubcategories']);

Step 2: Create Controllers

Create a controller class to handle category and subcategory data from database:

php artisan make:controller CategoryController

Define methods in CategoryController.php file to handle fetching categories and subcategories option data from the database and pass it on views using response:

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Category;

class CategoryController extends Controller
{
    public function getCategories()
    {
        $categories = Category::whereNull('parent_id')->get();
        return response()->json($categories);
    }

    public function getSubcategories($id)
    {
        $subcategories = Category::where('parent_id', $id)->get();
        return response()->json($subcategories);
    }
}

Step 3: Create Dropdowns in Blade View

In your Blade view file, create dropdowns for categories and subcategories using HTML and bootstrap 5:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Laravel 11 Dynamic Category and Subcategory Dropdown using Ajax - itcodstuff.com</title>
    <!-- Include Bootstrap 5 CSS -->
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/5.1.3/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <div class="container mt-5">
        <div class="row">
            <div class="col-md-6">
                <select id="category" name="category" class="form-select mb-3">
                    <option value="">Select Category</option>
                </select>
            </div>
            <div class="col-md-6">
                <select id="subcategory" name="subcategory" class="form-select mb-3">
                    <option value="">Select Subcategory</option>
                </select>
            </div>
        </div>
    </div>

    <!-- Include jQuery and Bootstrap 5 JS -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/5.1.3/js/bootstrap.bundle.min.js"></script>

</body>
</html>

Step 4: Write JavaScript for Ajax

Implement JavaScript/jQuery code to fetch category and subcategory options data dynamically using Ajax from database:

$(document).ready(function(){
    $('#category').change(function(){
        var category_id = $(this).val();
        if(category_id){
            $.ajax({
                url: '/subcategories/' + category_id,
                type: 'GET',
                dataType: 'json',
                success: function(data){
                    $('#subcategory').empty();
                    $('#subcategory').append('<option value="">Select Subcategory</option>');
                    $.each(data, function(key, value){
                        $('#subcategory').append('<option value="'+value.id+'">'+value.name+'</option>');
                    });
                }
            });
        }
    });

    $.ajax({
        url: '/categories',
        type: 'GET',
        dataType: 'json',
        success: function(data){
            $('#category').empty();
            $('#category').append('<option value="">Select Category</option>');
            $.each(data, function(key, value){
                $('#category').append('<option value="'+value.id+'">'+value.name+'</option>');
            });
        }
    });
});

Step 5: Test Your Application

Run the php artisan serve command to run laravel application server:

php artisan serve

To test this application, open your browser and type the URL http://127.0.0.1:8000/category, and you should see a dropdown to select categories and subcategories.

Thanks for reading…..

Leave a Comment