Laravel 8 Dynamic Dependent Dropdown Using Ajax

Laravel 8 dynamic dependent dropdown using jQuery ajax tutorial. In this post, you will learn how to implement dynamic dependent dropdown in laravel 8 using jQuery ajax.

Also, i will write easy jQuery ajax code for laravel 8 dynamic dependent dropdown.

In this post, i will create jquery ajax categories and subcategories select dropdown in laravel 8 app. Or show subcategories according to selected category value in dropdown in laravel 8 using ajax.

Laravel 8 Dynamic Dependent Dropdown Using jQuery Ajax

  • Step 1 – Installing Laravel 8 Application
  • Step 2 – Database Configuration
  • Step 3 – Creating Model & Migration
  • Step 4 – Make Routes
  • Step 5 – Creating Controller
  • Step 6 – Create Blade View
  • Step 7 – Start Development Server
  • Step 8 – Run This App On Browser

Step 1 – Installing Laravel 8 Application

In step 1, open your terminal and navigate to your local web server directory using the following command:

//for windows user
cd xampp/htdocs

//for ubuntu user
cd var/www/html

Then install laravel 8 latest application using the following command:

composer create-project --prefer-dist laravel/laravel Laravel8

Step 2 – Database Configuration

In step 2, open your downloaded laravel 8 app into any text editor. Then find .env file and configure database detail like following:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=db name
DB_USERNAME=db user name
DB_PASSWORD=db password

Step 3 – Creating Model & Migration

In step 3, open command prompt and navigate to your project by using the following command:

cd / Laravel8

Then create model and migration file by using the following command:

php artisan make:model Category -m

The above command will create two files into your laravel 8 ajax dynamic dropdown tutorial app, which is located inside the following locations:

  • Laravel8/app/Models/Category.php
  • Laravel8/database/migrations/create_categories_table.php

So, find create_events_table.php file inside Laravel8/database/migrations/ directory. Then open this file and add the following code into function up() on this file:

    public function up()
    {
        Schema::create('categories', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->unsignedInteger('parent_id')->nullable();
            $table->timestamps();
        });
    }

Next navigate to app and open Category.php model file. Then update the following code into your app/Category.php file as follow:

<?php

namespace App\Models;

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

class Category extends Model
{
    protected $guarded = [];
    
    public function subcategories(){
        return $this->hasMany('App\Category', 'parent_id');
    }
}

Now, open again your terminal and type the following command on cmd to create tables into your selected database:

php artisan migrate

Step 4 – Create Routes

In step 4, open your web.php file, which is located inside routes directory. Then add the following routes into web.php file:

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\FullCalendarController;

Route::get('dynamic-dropdown', [DynamicDropDownController::class, 'index']);
Route::post('fetch', [DynamicDropDownController::class, 'fetch']);

Step 5 – Creating Controller

In step 5, create dynamic dropDown controller by using the following command:

php artisan make:controller DynamicDropDownController

The above command will create DynamicDropDownController.php file, which is located inside Laravel8/app/Http/Controllers/ directory.

So open DynamicDropDownController.php file and add the following code into it:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\Category;

use response;

class DynamicDropDownController extends Controller
{
    public function index(Request $request)
    {
          
      $cat= Category::where('parent_id',0)->get();
     
      return view('category',["categories" => $cat]);
    }    


    public function fetch(Request $request)
    {
         
        $parent_id = $request->cat_id;
         
        $subcategories = Category::where('id',$parent_id)
                              ->with('subcategories')
                              ->get();
        return response()->json([
            'subcategories' => $subcategories
        ]);
    }   
}

Step 6 – Create Blade View

In step 6, create new blade view file that named category.blade.php inside resources/views directory. And add the following code into category.blade.php file:

<html lang="{{ app()->getLocale() }}">
   <head>
      <meta charset="utf-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <title>Laravel 8 jquery ajax categories and subcategories dropdown</title>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet">
      <meta name="csrf-token" content="{{ csrf_token() }}" />
   </head>
   <body>
      <div class="container" style="margin-top: 50px; margin-left: 300px">
         <div class="row">
            <div class="col-lg-6">
               <form action="">
                  <h4>Category</h4>
                  <select class="browser-default custom-select" name="category" id="category">
                     <option selected>Select category</option>
                     @foreach ($categoris as $item)
                     <option value="{{ $item->id }}">{{ $item->name }}</option>
                     @endforeach
                  </select>
                  <h4>Subcategory</h4>
                  <select class="browser-default custom-select" name="subcategory" id="subcategory">
                  </select>
               </form>
            </div>
         </div>
      </div>
   </body>
   <script type = "text/javascript" >
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
   $(document).ready(function() {
       $('#category').on('change', function(e) {
           var cat_id = e.target.value;
           $.ajax({
               url: "{{ route('subcat') }}",
               type: "POST",
               data: {
                   cat_id: cat_id
               },
               success: function(data) {
                   $('#subcategory').empty();
                   $.each(data.subcategories[0].subcategories, function(index, subcategory) {
                       $('#subcategory').append('<option value="' + subcategory.id + '">' + subcategory.name + '</option>');
                   })
               }
           })
       });
   }); 
</script>
</html>
  • The following laravel, jquery ajax code for show subcategories according to select category dropdown:
   $(document).ready(function() {
       $('#category').on('change', function(e) {
           var cat_id = e.target.value;
           $.ajax({
               url: "{{ route('subcat') }}",
               type: "POST",
               data: {
                   cat_id: cat_id
               },
               success: function(data) {
                   $('#subcategory').empty();
                   $.each(data.subcategories[0].subcategories, function(index, subcategory) {
                       $('#subcategory').append('<option value="' + subcategory.id + '">' + subcategory.name + '</option>');
                   })
               }
           })
       });
   }); 

Step 7 – Start Development Server

Finally, open your command prompt again and run the following command to start development server for your laravel 8 ajax fullcalendar example:

php artisan serve

Step 8 – Run This App On Browser

In step 8, open your browser and fire the following url into your browser:

http://127.0.0.1:8000/dynamic-dropdown

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *