Laravel with Packages | Laravel Dynamic Autocomplete Search using Select2 JS Ajax
Today, I am going to share with you how to make a dynamic autocomplete select dropdown from the database using the select2.js plugin in our laravel 5, laravel 6, laravel 7, laravel 8, and laravel 9 applications.
Why do we have to use autocomplete for our project ?, Sometimes we have more or thousands of records on our tables like users, products, tags, etc, so that can not possible to handle in manage from the select box. But you must require to make a select dropdown for your products tables then you can do it using the select2.js plugin. I already post autocomplete with Bootstrap Typeahead Plugin(Laravel 5 Autocomplete using Bootstrap Typeahead JS Example with Demo), But it is not possible with dropdowns like key and value, This post will help to implement select box autocomplete value using select2 js ajax.
In this tutorial, I going to give you a full example from scratch so you can easily understand and implement it on your project. You have to just follow a few steps to do this example. I also give you a demo for testing in Part 2. So you can also see the demo in the next part. After finishing this example you will see output like as bellow screenshot:
Preview:
Step 1: Install Laravel Application
we are going from scratch, So we require you to get a fresh Laravel 5.3 application using the bellow command, So open your terminal OR command prompt and run the bellow command:
composer create-project --prefer-dist laravel/laravel blog
Step 2: Database Configuration
In this step, we require to make database configuration, you have to add the following details on your .env file.
1. Database Username
2. Database Password
3. Database Name
In the .env file also available host and port details are, you can configure all details as in your system, So you can put like as below:
.env
DB_HOST=localhost
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret
Step 3: Create categories Table
In this step, we have to create migration for categories table using Laravel 5.3 PHP artisan command, so first fire bellow command:
php artisan make:migration create_category_table
After this command, you will find one file in the following path database/migrations and you have to put the below code in your migration file to create a categories table.
<?phpuse Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;class CreateCategoryTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
}/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('categories');
}
}
Now we require to run migration be bellow command:
php artisan migrate
After creating the “categories” table, we should have some dummy data for testing, So make sure that.
Step 4: Create Route
In this step, we need to create a route for the form layout file and another one for an ajax request. so open your routes/web.php file and add the following route.
routes/web.php
Route::get('select2-autocomplete', 'Select2AutocompleteController@layout');Route::get('select2-autocomplete-ajax', 'Select2AutocompleteController@dataAjax');
Ok Now we will see the last two steps on the next page, so click on the bellow button.
This part is part of the “Laravel 5 dynamic autocomplete search using select2 JS Ajax” article, In this part, you will see the logic of the database and blade template. So you have to follow this bellow remaining steps.
Step 5: Create Controller
At this point, now we should create a new controller as Select2AutocompleteController in this path app/Http/Controllers/Select2AutocompleteController.php. this controller will manage layout and select2 ajax requests, So run the bellow command to generate new controller:
php artisan make:controller Select2AutocompleteController
Ok, now put bellow content in the controller file:
app/Http/Controllers/Select2AutocompleteController.php
<?phpnamespace App\Http\Controllers;use Illuminate\Http\Request;use DB;class Select2AutocompleteController extends Controller{/*** Show the application layout.** @return \Illuminate\Http\Response*/public function layout(){return view('select2');}/*** Show the application dataAjax.** @return \Illuminate\Http\Response*/public function dataAjax(Request $request){$data = [];if($request->has('q')){$search = $request->q;$data = DB::table("categories")->select("id","name")->where('name','LIKE',"%$search%")->get();}return response()->json($data);}}
Step 6: Create a View
In the Last step, let’s create one blade file that will render a view of autocomplete task. In this file, I used cdn of bootstrap, jquery, and select2 plugin.
resources/views/select2.blade.php
<html lang="en"><head>
<title>Laravel 5 - Dynamic autocomplete search using select2 JS Ajax</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
</head><body><div class="container"><h2>Laravel 5 - Dynamic autocomplete search using select2 JS Ajax</h2>
<br/>
<select class="itemName form-control" style="width:500px;" name="itemName"></select></div><script type="text/javascript">$('.itemName').select2({
placeholder: 'Select an item',
ajax: {
url: '/select2-autocomplete-ajax',
dataType: 'json',
delay: 250,
processResults: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item.name,
id: item.id
}
})
};
},
cache: true
}
});</script></body>
</html>
Now we are ready to run our example so run the bellow command or a quick run:
php artisan serve
Now you can open bellow URL on your browser:
http://localhost:8000/select2-autocomplete
I hope it can help you...