Laravel 11 Autocomplete Search Using Select2 JS Example

May 04, 2024 | Laravel 11 Laravel


Hello Dev,

In this tutorial, I'll guide you through implementing Select2 AJAX autocomplete search functionality in a Laravel 11 application. Here's a breakdown of the steps involved:

1. Setup Laravel 11 App: Begin by setting up a new Laravel 11 application. You can do this by downloading the Laravel installer and creating a new project.

2. Database Setup: Run migrations to create the necessary tables. In this case, we'll create a `users` table where we'll perform our autocomplete search.

3. Create Dummy Users: Generate some dummy user data using Laravel Tinker or any other method you prefer. This data will be used to demonstrate the autocomplete functionality.

4. Create Blade File: Design a simple Blade file with an input field for the autocomplete search feature. This file will be responsible for rendering the HTML form.

5. Implement Select2 with AJAX: Utilize the Select2 JavaScript library to create an autocomplete textbox. Configure it to make AJAX requests to your Laravel backend for dynamic search results.

By following these steps, you'll be able to implement Select2 AJAX autocomplete search effortlessly in your Laravel 11 application. Let's dive into each step in detail.

Step 1: Install Laravel 11

If you haven't already, create a new Laravel project:

composer create-project --prefer-dist laravel/laravel example-app
Read Also: How to Implement Flash Message in Laravel 11? Step 2: Add Dummy Users
php artisan tinker

Then, insert some dummy data:

\App\Models\User::factory()->count(10)->create();
Step 3: Create Controller

Generate a Controller: Run php artisan make:controller UserController to create a new controller.

Add Methods: In UserController.php, add methods to handle the autocomplete functionality. For example:

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

Define Routes: In routes/web.php, add routes for the autocomplete functionality:

<?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');
Read Also: Get Last Executed Query in Laravel 11 Example Step 5: Create View File

Create a Blade File: Create a new Blade file, e.g., resources/views/searchDemo.blade.php, and include the necessary HTML and JavaScript for Select2:

<!DOCTYPE html>
<html>
<head>
    <title>Laravel 11 Autocomplete Search Using Select2 JS Example - ItErrorSolution.com</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/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">Laravel 11 Autocomplete Search Using Select2 JS Example - ItErrorSolution.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">
    $('#search').select2({
        placeholder: 'Select an user',
        ajax: {
            url: '/autocomplete',
            dataType: 'json',
            delay: 250,
            processResults: function (data) {
            return {
                results:  $.map(data, function (item) {
                    return {
                        text: item.name,
                        id: item.id
                    }
                })
            };
          },
          cache: true
        }
        placeholder: 'Search for a user',
        allowClear: true
    });
</script>
      
</body>
</html>
Step 6: Run the Application

Now, to run the Laravel application, please type the following command and press enter:

php artisan serve

Now, open your web browser and enter the provided URL to view the output of the application.

View Your Application
http://localhost:8000/autocomplete 

Thank you for your encouragement! If you have any questions or need further assistance, feel free to ask. I'm here to help!



Tags :
#Laravel 11
#Laravel
ItErrorSolution.com

ItErrorSolution.com

"Hey there! I'm a full-stack developer and proud owner of ItErrorSolution.com, based right here in India. I love nothing more than sharing handy tips and tricks with my fellow developers through easy-to-follow tutorials. When it comes to coding, I'm all about PHP, Laravel, Angular, Vue, Node, JavaScript, jQuery, CodeIgniter, and Bootstrap – been hooked on them forever! I'm all about putting in the work and staying committed. Ready to join me on this journey to coding?"