Laravel 9 Dynamic Dependent Dropdown Using Ajax

Hey Artisan,

In this Laravel 9 dependent dropdown tutorial, am going to discuss a brand new topic which is how to make a simple dependent dropdown using jquery ajax in the Laravel 9 application. In this tutorial, you will learn Laravel 9 dynamic dependent dropdown using ajax. 

To create this Laravel country state city dropdown, I will use a Category table to show you Laravel jquery ajax categories and subcategories dependent dropdown. Many developers create subcategory tables also to do it. But no need to create a subcategory model, we will create it with only a categories table.

I will create a category table that contains two fields one is the category name and the other is the parent_id. By using paren_id we will find out all subcategories from a category table.

I will make a self-relationship within the category table to show you laravel jquery ajax categories and subcategories select the dropdown menu item. Let's see how we can make it.

Preview : Before selecting category

larevel-9-dependent-dropdown-example

Preview : After selecting category

how-to-show-selected-value-in-dropdown-in-laravel-7-using-ajax

Preview: After selecting category

fetch-data-from-database-in-dropdownlist-in-laravel-onchange-ajax-jquery-in-laravel

Now let's start our example fetch data from the database in the dropdown list in Laravel onchange ajax jquery in Laravel 9 tutorial. 

 

Step 1: Create Category Model

Now we need a category model to get a category and dependent subcategory using ajax. So run the below command to create it

php artisan make:model Category -m

 

After doing it, open the newly created migration file and paste the following code.

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->id();
            $table->string('name');
            $table->unsignedInteger('parent_id')->nullable();
            $table->timestamps();
        });
    }

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

 

Now open the Category model to make a self-relationship. 

app/Category.php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    protected $guarded = [];

    public function subcategories(){

        return $this->hasMany('App\Category', 'parent_id');

    }
}

 

Now run the below command to migrate the category model.

php artisan migrate

 

After doing all of the above things, you need to insert some dummy data to create our laravel 9 dependent dropdown example with the demo tutorial. So make it like below

laravel-dependent-dropdown-example-with-demo

 

Step 2:  Create Route

Here we need two routes. from one route we will see our blade view and from another route, we will send our ajax request to the server. 

routes/web.php

use App\Category;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

Route::get('/', function () {

    $categoris = Category::where('parent_id',0)->get();
    
    return view('welcome',["categoris" => $categoris]);

});

Route::post('/subcat', function (Request $request) {

    $parent_id = $request->cat_id;
    
    $subcategories = Category::where('id',$parent_id)
                          ->with('subcategories')
                          ->get();

    return response()->json([
        'subcategories' => $subcategories
    ]);
   
})->name('subcat');

 

Read also : Create API Authentication using Laravel Passport

 

Step 3: Create Blade File

We are in the last step. So create welcome.blade.php and paste this below code. Here we will write our jquery code and we will send an ajax request from this file.

resources/view/welcome.blade.php

 

Read also: Laravel 9.x Custom Pagination Example Tutorial

 

Now you can check it after doing all of those above things. Hope it can help you.

 

#laravel #laravel-9x #ajax #jquery