Laravel Dynamic Ajax Dependent Dropdown

Laravel Dynamic Ajax Dependent Dropdown

Laravel dynamic dependent dropdown using ajax jquery. Here, you will learn how to create dynamic dependent dropdown using jquery ajax in laravel apps.

As well as learn, how to show selected subcategories dependent dropdown on selected category dropdown using jquery ajax in laravel.

In otherswords, How to retrieve subcategories data from database, when onchange selected category in dropdown list in laravel

This tutorial will guide you step by step to how to implement selected subcategories dropdown based on selected category dropdown using jQuery ajax in laravel apps. As well as learn, how to retrieve data from database on onchange select category dropdown using jQuery ajax in drop down list in laravel.

Note that, Here, we will not create separate tables for displaying selected subcategories based on selected category dropdowns. So, will use only a single table for category and subcategories.

Laravel Dynamic Dependent Dropdown Using jQuery Ajax

Follow the below simple and easy steps to create ajax dynamic dependent dropdown using jQuery in laravel app:

  1. Step 1: Install Laravel New App
  2. Step 2: Add Database Details
  3. Step 3: Create Model and Migration
  4. Step 4: Add Routes
  5. Step 5: Create Controllers By Artisan
  6. Step 6: Create Blade Views
  7. Step 7: Run Development Server

Step 1: Install Laravel New App

First of all, Open your terminal and run the following command to download or install laravel fresh new setup:

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

Step 2: Add Database Details

After that, open “.env” file and update the database name, username, and password in the env file:

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

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

php artisan make:model Category -m

Navigate database/migrations/ and open create_categorys_table.php file. Then update the following code into this file:

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 following command

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:

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

Next step, Navigate to “routes/web.php” file and add the following routes into your web.php file:

Route::get('cat', 'CategoryController@index');
Route::post('subcat', 'CategoryController@subCat');

Step 5: Create Controllers by Artisan

Next step, open your terminal and run the following command:

php artisan make:controller CategoryController 

This command will create CategoryController by the artisan command.

Next, Navigate to app/http/controller and open CategoryController.php.Then update the following methods into your controller file:

<?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:

<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

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

php artisan serve
http://localhost:8000/cat

This laravel, jquery ajax categories and subcategories, select dropdown app will look like:

laravel, jquery ajax categories and subcategories, select dropdown

Conclusion

In this tutorial, you have learned how to Laravel jQuery Ajax Categories and Subcategories Select Dropdown.

AuthorAdmin

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Node JS, Express JS, Vue JS, Angular JS, React Js, MySQL, MongoDB, REST APIs, Windows, Xampp, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL and Bootstrap from a starting stage. As well as demo example.

Leave a Reply

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