How to Select2 Ajax Autocomplete Search in Laravel 11?
Teams applying “How to Select2 Ajax Autocomplete Search in Laravel 11?” in a production project can use severance pay to record implementation, review and debugging time, then compare that effort with tests and shipped functionality instead of treating activity as performance by itself.
Before copying the example into a live application, confirm version-specific behaviour with the official Laravel website and test it against the project’s actual database and runtime.
Hi, Dev
In this guide, I'll walk you through implementing Select2 AJAX autocomplete search functionality within a Laravel 11 application.
Firstly, let's start by setting up a new Laravel 11 project and executing migrations to create the necessary 'users' table. Following that, we'll populate this table with some sample data using Laravel's Tinker.
Next, we'll craft a straightforward Blade view containing an input field for search purposes. Utilizing Select2 JavaScript library, we'll enhance this input field to feature autocomplete capabilities facilitated by AJAX requests.
Step for Laravel 11 Dynamic Autocomplete Search with Select2 Example
Step 1: Install Laravel 11
Step 2: Add Dummy Users
Step 3: Create Controller
Step 4: Create Routes
Step 5: Create View File
Run Laravel App
So, let's see the simple steps to complete this task.
Step 1: Install Laravel 11
This step is not required; however, if you have not created the Laravel app, then you may go ahead and execute the below command:
composer create-project laravel/laravel example-app
Step 2: Add Dummy Users
After creating the users table, we will create some dummy users using the Tinker factory. So let's create dummy records using the below command:
php artisan tinker
User::factory()->count(20)->create()
Step 3: Create Controller
At this point, we should create a new controller named SearchController. This controller will include two methods: one to return a view response and another to handle AJAX requests with JSON responses. Place the following content in the controller file:
app/Http/Controllers/SearchController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\View\View;
use Illuminate\Http\JsonResponse;
class SearchController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index(): View
{
return view('searchDemo');
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function autocomplete(Request $request): JsonResponse
{
$data = [];
if($request->filled('q')){
$data = User::select("name", "id")
->where('name', 'LIKE', '%'. $request->get('q'). '%')
->take(10)
->get();
}
return response()->json($data);
}
}
Step 4: Create Routes
In this step, we need to create a route for the datatables layout file and another one for getting data. So open your "routes/web.php" file and add the following route.
routes/web.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\SearchController;
Route::get('demo-search', [SearchController::class, 'index']);
Route::get('autocomplete', [SearchController::class, 'autocomplete'])->name('autocomplete');
Step 5: Create View File
In the last step, let's create `searchDemo.blade.php` (`resources/views/searchDemo.blade.php`) for layout and list all items code here and put the following code:
resources/views/searchDemo.blade.php
<!DOCTYPE html>
<html>
<head>
<title>How to Select2 Ajax Autocomplete Search in Laravel 11?- NiceSnippets.com</title>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js"></script>
</head>
<body>
<div class="container">
<div class="card mt-5">
<h3 class="card-header p-3">How to Select2 Ajax Autocomplete Search in Laravel 11? - NiceSnippets.com</h3>
<div class="card-body">
<form action="#" method="POST" enctype="multipart/form-data" class="mt-2">
@csrf
<select class="form-control" id="search" style="width:500px;" name="user_id"></select>
<div class="mb-3 mt-3">
<button type="submit" class="btn btn-success">Submit</button>
</div>
</form>
</div>
</div>
</div>
<script type="text/javascript">
var path = "{{ route('autocomplete') }}";
$('#search').select2({
placeholder: 'Select an user',
ajax: {
url: path,
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>
Run Laravel App:
All the required steps have been done, now you have to type the given below command and hit enter to run the Laravel app:
php artisan serve
Now, Go to your web browser, type the given URL and view the app output:
http://localhost:8000/demo-search
- How to Notifications With database Driver in Laravel 11?
- How to Send Email Via Notification in Laravel 11?
- How to Install and Configure Laravel 11 Debugbar?
- How to Like Dislike System in Laravel 11?
- How to Paginate a Model with Relationship in Laravel 11?
- Laravel 11 Upload Files to Amazon S3 Example
- Laravel 11 Send WhatsApp Messages Example
- Laravel 11 Rest API Authentication Using JWT Tutorial