Laravel Auto populate Dropdown with jQuery AJAX Example

Laravel 6 , Laravel , Laravel 7

Nicesnippets

515

22-06-2020


Hello Friends,

Today, I am going explain you how to create auto populate dropdown with jquery ajax in laravel. we will learn auto populate dropdown with jquery ajax example in laravel application.In this blog I will show you implement auto populate dropdown with jquery ajax in laravel app.

If you need auto populate dropdown with jquery ajax laravel.It is easy and simply to use auto-populate dropdown using jquery ajax in laravel application.

In this example, I am use category dropdown and sub category in auto populate dropdown laravel application using jquery ajax.

Here I will give full example for laravel auto complete dropdown with jquery ajax.So Lets Follow the bellow example step by stel.

Step 1 : Install Laravel Fresh App

In this step, You can install laravel fresh app. So open terminal and put the bellow command.

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

Step 2 : Setup Database Configuration

After successfully install laravel app thenafter configure databse setup. We will open ".env" file and change 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 Table Migration and Model

In this step we have to create migration for categories and subcategories table and Category and SubCategory Model using Laravel php artisan command, so first fire bellow command:

php artisan make:model Category -m

After this command you have to put bellow code in your migration file for create bookd table.

/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');

}

}

Now we require to run migration be bellow command:

php artisan migrate

After you have to put bellow code in your Category model file for create books table.

app/Category.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Category extends Model

{

protected $fillable = ['name'];

}

successfully create categories modal and migration thenafter create subcategories migration and table :

php artisan make:model SubCategory -m

After this command you have to put bellow code in your migration file for create bookd table.

/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');

}

}

Now we require to run migration be bellow command:

php artisan migrate

After you have to put bellow code in your SubCategory model file for create books table.

app/SubCategory.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class SubCategory extends Model

{

protected $fillable = ['category_id','name'];

}

Step 3 : Create Route

now, we need to add route for Category controller in laravel application. so open your "routes/web.php" file and add following route.

app/web.php

Route::get('categories','CategoryController@index');

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

Step 4 : Create Controler

Here this step now we should create new controller as CategoryController. So run bellow command and create new controller.

php artisan make:controller CategoryController

After successfully run above command . So, let's copy bellow code and put on CategoryController.php file.

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

In last step. In this step we have to create index blade file.So finally you have to create following file and put bellow code:

/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>

Now we are ready to run our example so run bellow command for quick run:

php artisan serve

Now you can open bellow URL on your browser:

http://localhost:8000/categories

It will help you...


Recommended Posts