Dynamic Dependent Dropdown Laravel 10 jQuery Ajax(Category SubCategory)

Dynamic Dependent Dropdown Laravel 10 jQuery Ajax(Category SubCategory)

This post is based on dynamic dependent dropdown example. In this dynamic dependent dropdown example with Laravel 10 jQuery and Ajax we will learn how to change each category and get subcategories related to the changed category. I will show step by step how we build a dynamic dependent dropdown system with laravel 10.

When a category is change the subcategories wil display in the next dropdown box based on the selected category. This tutorial is focused on laravel 10 but you can use any laravel versions. So let's start the bellow steps to do this dependent dropdown example.

 

Step 1: Install laravel

 

Execute the bellow code to install a fresh laravel project or you can use user existing project.

composer create-project laravel/laravel dynamic-dependent-dropdown

 

Step 2: Connect Database

 

Create a database and update your .env file with the newly created database information.

DB_DATABASE=dynamic-dependent-dropdown
DB_USERNAME=root
DB_PASSWORD=

 

 

Step 3: Model and Migration

 

In this step we will create Category and Subcategory models and two migrations file using the  -m argument. So run the bellow command:

php artisan make:model Category -m
php artisan make:model SubCategory -m

 

Now update the migrations file as show bellow

_categories_table.php

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('categories', function (Blueprint $table) {
            $table->id();
            $table->string('category');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('categories');
    }
};

 

_subcategories_table.php

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('subcategories', function (Blueprint $table) {
            $table->id();
            $table->string('subcategory');
            $table->bigInteger('category_id');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('subcategories');
    }
};

 

Also update the Category and Subcategory models

Category.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    use HasFactory;

    protected $fillable = ['name'];
}

 

Subcategory.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Subcategory extends Model
{
    use HasFactory;

    protected $fillable = ['name','category_id'];

}

 

Now run the bellow artisan command

php artisan migrate

 

 

Step 4: Create Seeder

 

In this step, we will create "CategorySubcategorySeeder" file to create dummy records. so let's create seeder and run it.

 

Create Seeder file using below command:

php artisan make:seeder CategorySubcategorySeeder

 

let's update following code on seeder file:

<?php

namespace Database\Seeders;

use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use App\Models\Category;
use App\Models\Subcategory;


class CategorySubcategorySeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {

        // First Category Data
        $category = Category::create(['name' => 'T-Shirt']);
        $subcategory = Subcategory::create(['category_id' => $category->id, 'name' => 'Casual T-Shirt']);

  
        // Second Category Data
        $category = Category::create(['name' => 'Shoes']);
        $subcategory = Subcategory::create(['category_id' => $category->id, 'name' => 'Casual Shoes']);
  
    }
}

 

Next, run seeder with below command to insert data into categories and subcategories table:

php artisan db:seed --class=CategorySubcategorySeeder

 

 

Step 5: Create Routes

 

We have to create two routes one is for display the dynamic dropdown page and another is for get subcategories based on their categories.

Let's create required routes:

web.php

Route::get('dropdown-page',[DropdownController::class, 'dropdown_page'])->name('dropdown.page');
Route::post('get-subcategory',[DropdownController::class, 'get_subcategory'])->name('get.subcategory');

 

 

Step 6: Create Controller and Update

 

In this  step we will create controller and update the controller with two methods for category and subcategories.

Run the command to create a controller:

php artisan make:controller DropdownController

 

Now Update the DropdownController like bellow

DropdownController.php

<?php

namespace App\Http\Controllers;

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


class DropdownController extends Controller
{
    //dropdown page view

    public function dropdown_page()
    {
        $categories = Category::all();
        return view('dropdown-page',compact('categories'));
    }

      //get subcategory
    public function get_subcategory(Request $request)
    {
        $subcategories = Subcategory::where('category_id', $request->category)->get();
        return response()->json([
            'status' => 'success',
            'subcategories' => $subcategories,
        ]);
    }
}

 

 

Step 7: Create Blade File

 

Now we will create a blade file and display our category. We also display subcategory when a category will change. Let's create a blade file and update with the following code.

dropdown-page.blade.php

 <!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>Dynamic Dependent Dropdown - WebJourney</title>
   <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet">
  </head>
  <body>

    <div class="container mt-5">
    	<div class="row">
    		<div class="col-md-3"></div>
    		<div class="col-md-6">
    			<form>
                    <h4 class="my5">Dynamic Dependent Dropdown - WebJourney</h4>
    				<div class="form-group my-3">
    					<label class="mb-1">Select Category</label>
    					<select name="name" id="category" class="form-control">
    						<option>Change Category</option>
                            @foreach($categories as $cat)
    						    <option value="{{ $cat->id }}">{{ $cat->name }}</option>
                             @endforeach
    					</select>
    				</div>
    				<div class="form-group my-3">
    					<label class="mb-1">Select Subcategory</label>
    					<select name="name" id="subcategory" class="form-control get_subcategory"></select>
    				</div>
    			</form>
    		</div>
    	</div>
    </div>


    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
    <script>
    	$.ajaxSetup({
		    headers: {
		        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
		    }
		});
    </script>

    <script>
        $(document).ready(function(){
            $(document).on('change','#category', function() {
                let category = $(this).val();
                $('#subcategory_info').show();
                $.ajax({
                    method: 'post',
                    url: "{{ route('subcategory.get') }}",
                    data: {
                        category: category
                    },
                    success: function(res) {
                        if (res.status == 'success') {
                            let all_options = "<option value=''>Select Sub Category</option>";
                            let all_subcategories = res.subcategories;
                            $.each(all_subcategories, function(index, value) {
                                all_options += "<option value='" + value.id +
                                    "'>" + value.name + "</option>";
                            });
                            $(".get_subcategory").html(all_options);
                        }
                    }
                })
            });
        });
    </script>
  </body>
</html>

 

Step 8: Test App

 

Run the server using the bellow command:

php artisan serve

Now hit the url http://127.0.0.1:8000/dropdown-page  and test the app.

 

 

 

 

If you like what you are reading, please think about buying us a coffee as a token of appreciation.

Buy Me A Coffee

We appreciate your support and are committed to providing you useful and informative content.

We are thankful for your ongoing support.

 

 

 

 

You May Read Bellow Articles:

 

 

Laravel 9 live search data in a table using ajax

 

How to send SMS in laravel 9 using Twilio SMS API-Webjourney

 

Laravel 9 pdf invoice generate and download with barryvdh dompdf

 

How to create multi language website by laravel 9

 

Laravel 10 multiple form validation on the same page-WebJourney

 

 Laravel 10 Breeze Authentication - WebJourney

 

Laravel 10 Ajax jQuery Crud with Pagination and Live Search

 

Laravel Naming Conventions Accepted by Laravel community

 

Laravel Shorter and More Readable Syntax - WebJourney

Tags

  • Share This: