Laravel 11 Select2 Ajax Autocomplete | websolutioncode.com
Laravel 11 Select2 Ajax Autocomplete | websolutioncode.com

Laravel 11 Select2 Ajax Autocomplete

INTRODUCTION

In modern web development, The success of an application greatly hinges on the quality of user interaction. An essential aspect contributing to this is the autocomplete search feature, known for its ability to significantly enrich user engagement and satisfaction levels.. Laravel, a popular PHP framework, provides developers with a powerful set of tools to create such features efficiently. In this article, we’ll explore how to implement Select2 Ajax autocomplete search in a Laravel 11 application, making your search functionality smooth and responsive.

Understanding Select2

Select2 is a jQuery-based replacement for select boxes. It enhances the traditional select input by providing searching, remote data sets, infinite scrolling, and many more features. Integrating Select2 with Laravel allows us to create dynamic and interactive autocomplete search fields effortlessly.

Prerequisites

Before we start, make sure you have the following installed on your system:

  • Laravel 11
  • Composer
  • NPM

Setting Up Laravel

If you haven’t already set up a Laravel project, you can do so by running the following command:

composer create-project --prefer-dist laravel/laravel autocomplete-search

Navigate to the project directory:

cd autocomplete-search

Installing Select2

Next, we need to install Select2 via npm. Run the following command in your terminal:

npm install select2

Implementation Steps

  1. Create a Route: Define a route to handle the Ajax request.
// routes/web.php
Route::get('search', 'SearchController@search')->name('search');

Create a Controller:

Generate a controller named SearchController.

php artisan make:controller SearchController

Write Search Logic:

In the SearchController, implement the logic to fetch data based on the search query.

// app/Http/Controllers/SearchController.php
public function search(Request $request)
{
    $query = $request->get('q');

    $results = YourModel::where('column', 'like', '%'.$query.'%')->get();

    return response()->json($results);
}

Create a Blade View:

Generate a Blade view where you will include the Select2 plugin.

<!-- resources/views/search.blade.php -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Laravel Select2 Ajax Autocomplete Search</title>
    <link href="{{ asset('css/app.css') }}" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css" rel="stylesheet">
</head>
<body>
    <div class="container mt-5">
        <select class="form-control select2" id="search">
            <option value="">Search...</option>
        </select>
    </div>

    <script src="{{ asset('js/app.js') }}"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js"></script>
    <script>
        $(document).ready(function() {
            $('.select2').select2({
                ajax: {
                    url: '{{ route('search') }}',
                    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>

Compile Assets:

Compile your assets using Laravel Mix.

npm run dev

Run Your Application:

Start your Laravel server and navigate to the URL where you’ve set up your application.

php artisan serve

Conclusion

In this tutorial, we’ve seen how to implement Select2 Ajax autocomplete search in a Laravel 11 application. By leveraging Select2’s capabilities along with Laravel’s powerful backend, we can create dynamic and responsive search functionality that enhances the user experience of our web applications. Feel free to customize this implementation further to suit your specific requirements and design preferences. Happy coding!

Leave a Reply