In this tutorial you will learn about the Laravel Dynamic Ajax Dependent Dropdown and its application with practical example.
In this Laravel dynamic dependent dropdown using ajax jquery tutorial I’ll show you how to create dynamic dependent dropdown using jquery ajax in laravel. In this tutorial you will learn to create ajax dynamic dependent dropdown using jquery ajax. In this article I’ll demonstrate how to show selected subcategories dependent dropdown on selected category dropdown using jquery ajax in laravel.
Laravel Dynamic Ajax Dependent Dropdown
- Step 1: Install Laravel New App
- Step 2: Add Database Details
- Step 3: Create Model and Migration
- Step 4: Add Routes
- Step 5: Create Controllers By Artisan
- Step 6: Create Blade Views
- Step 7: Run Development Server
Step 1: Install Laravel New App
First of all we need to create a fresh laravel project, download and install Laravel using the below command
1 |
composer create-project --prefer-dist laravel/laravel blog |
Step 2: Add Database Details
Now, lets create a MySQL database and connect it with laravel application. After creating database we need to set database credential in application’s .env file.
1 2 3 4 5 6 |
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 Modal and Migration
Now, in this step we will create model and migration file. Please run the following command:
1 |
php artisan make:model Category -m |
Navigate database/migrations/ and open create_categorys_table.php file. Then update the following code into this file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
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, run the migration to create database table using following artisan command:
1 |
php artisan migrate |
Next navigate to app and open Category.php model file. Then update the following code into your app/Category.php file as follow:
1 2 3 4 5 6 7 8 9 |
namespace App; use Illuminate\Database\Eloquent\Model; class Category extends Model { protected $guarded = []; public function subcategories(){ return $this->hasMany('App\Category', 'parent_id'); } } |
Step 4: Add Routes
After this, we need to define routes in “routes/web.php” file. Lets open “routes/web.php” file and add the following routes in it.
routes/web.php
1 2 |
Route::get('cat', 'CategoryController@index'); Route::post('subcat', 'CategoryController@subCat'); |
Step 5: Create Controllers by Artisan
Now, lets create a controller named CategoryController using command given below –
1 |
php artisan make:controller CategoryController |
This command will create CategoryController by the artisan command.
Now, go to app/http/controller and open CategoryController.php.Then put the following methods into your controller file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
<?php namespace App\Http\Controllers; use App\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, you need to create one blade views file for rendering data on it. So navigate to resources/views folder and create the blade view as following:
Create first file name category.blade.php and update the following code into it:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
<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, 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
Now we are ready to run our example so lets start the development server using following artisan command –
1 |
php artisan serve |
Now, open the following URL in browser to see the output –
1 |
http://localhost:8000/cat |