Laravel 10 Ajax Dynamic Dependent Dropdown Example

In this tutorial, I will show you how to create a dynamic dependent dropdown in Laravel 10 using Ajax.

We will use the jQuery library to make an Ajax request to the server and get the data from the database. Then we will populate the dropdown with the data.

Let’s get started.

Step 1: Create Database Table

First, we need to create a database table to store the data. We will use the following SQL query to create a table called “countries” in the database.

CREATE TABLE `countries` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`code` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Step 2: Create Model and Migration

Next, we need to create a model and migration for the countries table. We will use the following command to generate the model and migration.

php artisan make:model Country -m

This command will create a model and migration for the countries table.

Step 3: Add Data to Database

Now, we need to add some data to the database. We will use the following SQL query to insert some data into the countries table.

INSERT INTO `countries` (`name`, `code`) VALUES
(‘United States’, ‘US’),
(‘United Kingdom’, ‘UK’),
(‘Canada’, ‘CA’),
(‘Australia’, ‘AU’);

Step 4: Create Routes

Next, we need to create routes for our application. We will use the following code to create routes for our application.

Route::get(‘/’, ‘CountryController@index’);
Route::get(‘get-states/{id}’, ‘CountryController@getStates’);

Step 5: Create Controller

Now, we need to create a controller for our application. We will use the following command to generate a controller.

php artisan make:controller CountryController

This command will create a controller called CountryController.

Step 6: Add Code to Controller

Next, we need to add the following code to the CountryController.

states;
return response()->json($states);
}
}

Step 7: Create View

Now, we need to create a view for our application. We will use the following code to create a view.




Laravel 10 Ajax Dynamic Dependent Dropdown Example


Laravel 10 Ajax Dynamic Dependent Dropdown Example


Step 8: Add Code to View

Finally, we need to add the following code to the view.

@extends(‘layouts.app’)

@section(‘content’)

Dynamic Dependent Dropdown in Laravel 10 using Ajax
@if (session(‘status’))

@endif

@include(‘dynamic_dependent_dropdown’)

@endsection

That’s it. Now you have successfully created a dynamic dependent dropdown in Laravel 10 using Ajax.
[ad_1]

if you are creating a web app in Laravel. And in that, you have some forms, which need to use dependent dropdown. then what do you do?

In this tutorial, you will learn how to create a ajax category & subcategories dynamic dependent dropdown in Laravel 10 web apps.

Laravel 10 Ajax Dynamic Dependent Dropdown Example

By following these steps, you can create dynamic dependent dropdown using jQuery ajax in laravel apps:

  • Step 1 – Create New Laravel 10 Project
  • Step 2 – Setup Database with Laravel Project
  • Step 3 – Create Migration and Model File
  • Step 4 – Add Routes
  • Step 5 – Create Controllers By Artisan
  • Step 6 – Create Blade Views
  • Step 7 – Run Development Server
  • Step 8 – Test This App

Step 1 – Create New Laravel 10 Project

Firstly, Open your terminal or command prompt.

Then execute the following command on the terminal to download or install Laravel 10 fresh new setup:

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

Step 2 – Setup Database with Laravel Project

In this step, visit your laravel app root directory and find the .env file.

Then configure database details in the .evn file, like the following:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=Enter_Your_Database_Name
DB_USERNAME=Enter_Your_Database_Username
DB_PASSWORD=Enter_Your_Database_Password

Step 3 – Create Migration and Model File

In this step, create category table migration and create category Modal by using the following command:

php artisan make:model Category -m

After that, you need to visit the database/migrations/ directory and then open the create_categorys_table.php file. And add the following code into this file:

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

Now run the following command on the terminal to create tables on database:

php artisan migrate

Then visit the app/Models directory and open the Category.php model file. And then add the following code into it:

<?php

namespace App\Models;

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

class Category extends Model
{
    use HasFactory;

    public function subcategories(){
        return $this->hasMany('App\Models\Category', 'parent_id');
    }
}

Step 4 – Add Routes

Now, Visit to routes directory and open “/web.php” file. Then add the following routes to your web.php file:

use App\Http\Controllers\CategoryController;

Route::get('cat', [CategoryController::class, 'index']);
Route::post('subcat', [CategoryController::class, 'subCat']);

Step 5 – Create Controllers by Artisan

In this step, you need to create a controller file. So execute the following command on the terminal to create a controller file that named CategoryController:

php artisan make:controller CategoryController 

This command will create CategoryController by the artisan command.

Then visit to app/http/controller directory and open CategoryController.php. Then update the following methods into your controller file:

<?php
namespace App\Http\Controllers;
use App\Models\Category;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
class CategoryController extends Controller
{
    public function index(Request $request)
    {
         
      $categoris = Category::where('parent_id',0)->get();
    
      return view('category',["categoris" => $categoris]);
    }    
    public function subCat(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 Views

In this step, create one blade views file for rendering data on it. So navigate to resources/views folder and create the blade view as following:

Create file name category.blade.php and update the following code into it:

<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 10 jquery ajax categories and subcategories, select 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>
<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>
</body>
</html> 

Step 7 – Run Development Server

In this step, Execute the following php artisan serve command to start your server locally:

php artisan serve

Step 8 – Test This App

Now, open browser and hit the following url on it for test this app:

http://localhost:8000/cat

Conclusion

In this tutorial, you have learned how to create dynamic dependent dropdown using Ajax in Laravel 10 app.

Recommended Laravel Posts

[ad_2]

Jaspreet Singh Ghuman

Jaspreet Singh Ghuman

Jassweb.com/

Passionate Professional Blogger, Freelancer, WordPress Enthusiast, Digital Marketer, Web Developer, Server Operator, Networking Expert. Empowering online presence with diverse skills.

jassweb logo

Jassweb always keeps its services up-to-date with the latest trends in the market, providing its customers all over the world with high-end and easily extensible internet, intranet, and extranet products.

GSTIN is 03EGRPS4248R1ZD.

Contact
Jassweb, Rai Chak, Punjab, India. 143518
Item added to cart.
0 items - 0.00