Laravel Dynamic Autocomplete Search using Select2 JS Ajax - Part 2

By Hardik Savani November 5, 2023 Category : Laravel

After complete 4 steps in our Part 1, we have to proceed next step from Part 2. In this part we write code for how to manage controller method and how to give response them. We also write code for view blade layout files.

This part is hart of "Laravel 5 dynamic autocomplete search using select2 JS Ajax" article, In this part you will see the logic of database and blade template. So you have to follow this bellow remaining steps.

Step 5: Create Controller

In this point, now we should create new controller as Select2AutocompleteController in this path app/Http/Controllers/Select2AutocompleteController.php. this controller will manage layout and select2 ajax request, So run bellow command for generate new controller:

php artisan make:controller Select2AutocompleteController

Ok, now put bellow content in controller file:



namespace 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 = [];


$search = $request->q;

$data = DB::table("categories")





return response()->json($data);



Step 6: Create View

In Last step, let's create one blade file that will render view of autocomplete task. In this file i used cdn of bootstrap, jquery and select2 plugin.


<html lang="en">


<title>Laravel 5 - Dynamic autocomplete search using select2 JS Ajax</title>

<script src=""></script>

<link href="" rel="stylesheet" />

<link href="" rel="stylesheet" />

<script src=""></script>



<div class="container">

<h2>Laravel 5 - Dynamic autocomplete search using select2 JS Ajax</h2>


<select class="itemName form-control" style="width:500px;" name="itemName"></select>


<script type="text/javascript">


placeholder: 'Select an item',

ajax: {

url: '/select2-autocomplete-ajax',

dataType: 'json',

delay: 250,

processResults: function (data) {

return {

results: $.map(data, function (item) {

return {







cache: true






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

php artisan serve

Now you can open bellow URL on your browser:


I hope it can help you...