Hello! In this article, I’ll show you how I implemented a Select2 autocomplete search in Laravel 12 using Ajax. This is super useful when you want a search box that loads results from the database while typing — like user names, tags, or categories.
The Select2 plugin gives you a clean, searchable dropdown, and with Laravel's backend and a little jQuery, we’ll make it dynamic and fast.
Laravel 12 Select2 Ajax Example
Install laravel 12 using the following command.
laravel new select2-autocomplete
Let’s say we want to search users. Run the following:
php artisan make:model User -m
In the migration file, add:
$table->string('name');
Then run:
php artisan migrate
Add some dummy users using tinker or a seeder.
Define the routes in the web.php file.
use App\Http\Controllers\UserController;
Route::get('user-search', [UserController::class, 'search'])->name('user.search');
Route::get('form', [UserController::class, 'form']);
Now, create a controller using the following command.
php artisan make:controller UserController
Then in UserController.php
:
use App\Models\User;
use Illuminate\Http\Request;
public function form()
{
return view('form');
}
public function search(Request $request)
{
$search = $request->get('q');
$users = User::where('name', 'like', '%' . $search . '%')->get();
$response = [];
foreach ($users as $user) {
$response[] = [
"id" => $user->id,
"text" => $user->name
];
}
return response()->json($response);
}
Create resources/views/form.blade.php
:
<!DOCTYPE html>
<html>
<head>
<title>Laravel 12 Select2 Ajax Example</title>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css" rel="stylesheet" />
</head>
<body>
<h2>Select2 Ajax Search in Laravel 12</h2>
<select class="user-select" style="width:300px"></select>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>
<script type="text/javascript">
$('.user-select').select2({
placeholder: 'Search user',
ajax: {
url: '{{ route("user.search") }}',
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term
};
},
processResults: function (data) {
return {
results: data
};
},
cache: true
}
});
</script>
</body>
</html>
If you found this useful, feel free to bookmark or share it. Happy coding!
You might also like: