laravel dynamic dependent dropdown using ajax

Dynamic dependent dropdown using ajax in Laravel

In this tutorial, I will give you an example of the “How to create dynamic dependent dropdown using ajax in Laravel“, So you can easily apply it with your laravel 5, laravel 6, laravel 7, and laravel 8 application.

First, what we’re doing here, This is the example :

We will create to show subcategories of a specific category in a dropdown (Subcategories according to category) in Laravel.

This means, when we select a category on the dropdown, The all related subcategory, will appear on the subcategory Select box Dropdown in the blade file.

Preview : Before selecting a category


Preview : After selecting a category



Generating Migrations :

We create 3 Tables for storing categories, subcategories and product data in database.

  • categories
  • subcategories
  • products
php artisan make:migration create_categories_table
php artisan make:migration create_subcategories_table
php artisan make:migration create_products_table


Migration Structures :

database\migrations\categories

<?php

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

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

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

database\migrations\subcategories

<?php

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

class CreateSubcategoriesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('subcategories', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->unsignedBigInteger('cat_id');
            $table->string('name');
            $table->index(['created_at']);
            $table->timestamps();
            $table->foreign('cat_id')
            ->references('id')
            ->on('categories')
            ->onDelete('cascade');
        });
    }

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

database\migrations\products

<?php

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

class CreateProductsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('cat_id');
            $table->unsignedBigInteger('sub_cat_id');
            $table->string('name');
            $table->string('description');
            $table->timestamps();
        });
    }

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


Run Migration :

php artisan:migrate


Create Models :

Now, we create 3 Models for Category, Subcategory and Product.

  • Category
  • Subcategory
  • Product
php artisan make:model Category
php artisan make:model Subcategory
php artisan make:model Product

App\Model\Category

<?php

namespace App\Model;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    protected $table = 'categories';
}

App\Model\Subcategory

<?php

namespace App\Model;

use Illuminate\Database\Eloquent\Model;

class Subcategory extends Model
{
    protected $table = 'subcategories';
    protected $fillable = ['cat_id'];

    public function catname()
    {
        return $this->hasOne(Category::class,'id','cat_id');
    }
}

Create a Relationship in the subcategory Model for getting Category data, like id, name, etc.

App\Model\Product

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    protected $table = 'products';
    protected $fillable = ['id','cat_id','sub_cat_id','name','description'];

    public function CategoryData()
    {
    return $this->hasOne('App\Model\Category','id','cat_id');
    }
}

Create Controller:

php artisan make:controller ProductController

Create Routes :

routes\web.php

#Get Subcategory according to Category

Route::get('/list-category','ProductController@listcategory')->name('list.category');
Route::get('/add-subcategory','ProductController@createsubcategory')->name('create.subcategory');
Route::post('/store-subcategory','ProductController@storesubcategory')->name('store.subcategory');
Route::get('/list-subcategory','ProductController@listsubcategory')->name('list.subcategory');
Route::get('/add-product','ProductController@createproduct')->name('create.product');
Route::get('/ajax-get-subcat', 'ProductController@fetchsubcategory');
Route::post('/store-product','ProductController@storeproduct')->name('store.product');


App\Http\Controllers\ProductController

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Model\Category;
use App\Model\Product;
use App\Model\Subcategory;


class ProductController extends Controller
{

    public function listcategory(){
        $catdata = Category::get();
        return view('category.list',compact('catdata'));
    }

    public function createsubcategory(){
        $category = Category::get();
        return view('subcategory.create',compact('category'));
    }

    public function storesubcategory(Request $request)
    {
        $subcatdata = new Subcategory();
        $subcatdata->cat_id = $request->category;
        $subcatdata->name   = $request->subcat;
        $subcatdata->save();
        dd('success,Subcategory Added Successfully...!');
    }

    public function listsubcategory(){

        $subcatdata = Subcategory::with('catname')->get();
        return view('subcategory.list',compact('subcatdata'));
    }

    public function createproduct(){
        $category = Category::get();
        return view('product.create',compact('category'));
    }

    #Fetch Subcategory
    public function fetchsubcategory(Request $request) {
        $cat = $request->cat_id;
        $subcat = Subcategory::select('id','cat_id','name')->where('cat_id', $cat)->get();
        return response()->json($subcat);
    }

    #Store Product
    public function storeproduct(Request $request){
        $product = new Product();
        $product->cat_id = $request->cat;
        $product->sub_cat_id = $request->sub_cat;
        $product->name = $request->product_name;
        $product->description = $request->description;
        $product->save();
        dd('success,Product Added Successfully...!');
    }
}


We have already some data for testing in the categories table.

resources\views\category\list.blade.php

<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
   </head>
   <body>
      <div class="container">
         <h3>Category List | Subcategories of specific category in a dropdown in laravel</h3>
         <table class="table">
            <thead>
               <tr>
                  <th>S.no</th>
                  <th>Category Name</th>
               </tr>
            </thead>
            <tbody>
               @foreach($catdata as $key => $data)
               <tr>
                  <td>{{ $key+1 }}</td>
                  <td>{{ $data->name }}</td>
               </tr>
            </tbody>
            @endforeach
         </table>
      </div>
   </body>
</html>

resources\views\subcategory\create.blade.php

<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
   </head>
   <body>
      <div class="container">
         <br>
         <h3>Subcategory Add | Subcategories of specific category in a dropdown in laravel</h3>
         <br>
         <br>
         <div class="card">
            <form method="post" action="{{route('store.subcategory')}}">
               @csrf
               <div class="card-header">Please fill up all the Field's.</div>
               <div class="card-body">
                  <div class="row">
                     <div class="col-md-6">
                        <label for="category">Category :</label>
                        <select class="form-control select2" name="category" required>
                           <option>Select Category</option>
                           @foreach ($category as $cat)
                           <option value="{{$cat->id}}">{{$cat->name}} </option>
                           @endforeach
                        </select>
                     </div>
                     <div class="col-md-6">
                        <label for="subcategory">Subcategory Name :</label>
                        <input type="text" class="form-control" placeholder="Enter subcategory name" name="subcat" required>
                     </div>
                  </div>
               </div>
               <div class="col-md-3">
                  <button type="submit" class="btn btn-block btn-info btn-sm">Save</button>
               </div>
               <br/>
         </div>
         </form>
      </div>
   </body>
</html>

resources\views\subcategory\list.blade.php

<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
   </head>
   <body>
      <div class="container">
         <h3>Subcategory List | Subcategories of specific category in a dropdown in laravel</h3>
         <table class="table">
            <thead>
               <tr>
                  <th>S.no</th>
                  <th>CategoryName</th>
                  <th>Subcategory Name</th>
               </tr>
            </thead>
            <tbody>
               @foreach($subcatdata as $key => $data)
               <tr>
                  <td>{{ $key+1 }}</td>
                  <td>{{$data->catname->name}}</td>
                  <td>{{$data->name}}</td>
               </tr>
            </tbody>
            @endforeach
         </table>
      </div>
   </body>
</html>

resources\views\product\create.blade.php

<!DOCTYPE html>
<html lang="en">
   <head>
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
   </head>
   <body>
      <div class="container">
      <br>
      <h3>Productp Add | Subcategories of specific category in a dropdown in laravel</h3>
      <br>
      <div class="card">
         <form method="post" action="{{route('store.product')}}">
            @csrf
            <div class="card-header">Please fill up all the Field's.</div>
            <div class="card-body">
               <div class="row">
                  <div class="col-md-4">
                     <label for="category">Category <span class="text-danger">*</span></label>
                     <select class="form-control" name="cat" id="cat" style="width: 100%;" required>
                        <option>Select Category</option>
                        @foreach ($category as $cat)
                        <option value="{{$cat->id}}">{{ $cat->name }}</option>
                        @endforeach
                     </select>
                  </div>
                  <div class="col-md-4">
                     <label for="subcat">Subcategory<span class="text-danger">*</span></label>
                     <select class="form-control select2" name="sub_cat" id="subcat" required>
                        <option value="">Select Subcategory</option>
                     </select>
                  </div>
                  <div class="col-md-4">
                     <label for="Product Name">Product Name :</label>
                     <input type="text" class="form-control" placeholder="Enter Product name" name="product_name" required>
                  </div>
               </div>
               <div class="row mt-4" >
                  <div class="col-md-6">
                     <label for="Product Description">Product Description :</label>
                     <textarea class="form-control" name="description" rows="4" cols="45" maxlength="400"></textarea>
                  </div>
               </div>
               <br>
               <div class="col-md-3">
                  <button type="submit" class="btn btn-block btn-info btn-sm">Save</button>
               </div>
               <br/>
            </div>
         </form>
      </div>
   </body>
</html>
<script>
   $('#cat').on('change',function(e){
   var cat_id = e.target.value;
   $.get('/ajax-get-subcat?cat_id=' + cat_id,function(data){
      $('#subcat').empty();
      $.each(data,function(index,areaObj){
      $('#subcat').append('<option value="'+areaObj.id+'">'+areaObj.name+'</option>');
      });
   });
   });
</script>
}

After following these steps successfully, you are able to show subcategories of a specific category in a dropdown in Laravel.


In this article, we learned “jQuery Ajax Dynamic Dependent Dropdown in Laravel”, I hope this article will help you with your Laravel application Project.

Also Read : Multiple Database Connection in Laravel.