Hello Devs,

In this tutorial, we are going to learn how to create auto populate dropdown with jquery ajax in laravel.

Follow this step by step guide given below:




Step 1 : 

Install Laravel App

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



Step 2 : 

Setup Database Configuration

 open ".env" file and change the database

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 Table Migration and Model

php artisan make:model Category -m


/database/migrations/2020_05_27_100722_create_categories_table.php

<?php

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->timestamps();
        });
    }

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

Run this command:

php artisan migrate


app/Category.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    protected $fillable = ['name'];
}

Run this command:

php artisan make:model SubCategory -m


/database/migrations/2020_05_27_100722_create_categories_table.php

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateSubCategoriesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('sub_categories', function (Blueprint $table) {
            $table->id();
            $table->integer('category_id');
            $table->string('name');
            $table->timestamps();
        });
    }

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


Run this command:

php artisan migrate


app/SubCategory.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class SubCategory extends Model
{
    protected $fillable = ['category_id','name'];
}



Step 4 : 

Create Route app/web.php

Route::get('categories','CategoryController@index');
Route::get('categories/{id}','CategoryController@getCategory')->name('categories');



Step 5 : 

Create Controller

php artisan make:controller CategoryController

app/http/controller/CategoryController.php

<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Category;
use App\SubCategory;

class CategoryController extends Controller
{
    public function index()
    {
        $categories = Category::get();
        return view('categories',compact('categories'));
    }

    public function getCategory($category_id)
    {
        $data = SubCategory::where('category_id',$category_id)->get();
        \Log::info($data);
        return response()->json(['data' => $data]);
    }

}



Step 5 : 

Create Blade File /resources/views/index.blade.php

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>  
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
</head>
<body>
    <div class="container mt-5">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header">Dashboard</div>
                    <div class="card-body">
                        <div class="form-group">
                            <label>Category:</label>
                            <select name="category" id="category" class="form-control">
                                <option value="0">-- Select Cateory --</option>
                                @foreach($categories as $category)
                                    <option value="{{ $category->id }}">{{ $category->name }}</option>
                                @endforeach
                            </select>
                        </div>
                        <div class="form-group">
                            <label>Sub Category:</label>
                            <select name="sub_category" id="subCategory" class="form-control">
                                <option value="0">-- Select Sub Category --</option>
                            </select>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <script type="text/javascript">
        $(document).ready(function () {
           $('#category').change(function () {
             var id = $(this).val();

             $('#subCategory').find('option').not(':first').remove();

             $.ajax({
                url:'category/'+id,
                type:'get',
                dataType:'json',
                success:function (response) {
                    var len = 0;
                    if (response.data != null) {
                        len = response.data.length;
                    }

                    if (len>0) {
                        for (var i = 0; i<len; i++) {
                             var id = response.data[i].id;
                             var name = response.data[i].name;

                             var option = "<option value='"+id+"'>"+name+"</option>"; 

                             $("#subCategory").append(option);
                        }
                    }
                }
             })
           });
        });
    </script>
</body>
</html>


Run this command:

php artisan serve


Open this URL:

http://localhost:8000/categories


I hope this example helps you.