How to Create AJAX Autocomplete Search in Laravel 8 with Select2

How to build AJAX Autocomplete search in Laravel 8 using Select2 library. This tutorial is going to cover some of the core concepts of Laravel 8 Autocomplete search, some tricks to use AJAX to build a dynamic autocomplete search in Laravel, integrating Bootstrap CSS framework in Laravel to design autocomplete search.

Autocomplete or predictive text, is a trait through which web or mobile application foretells the rest of the word a user types. In android device, it is known as the predictive text. You will adjoin AJAX to make the autocomplete search work in Laravel.

Ajax is a popular web development mechanism used in client-side to build an asynchronous web or mobile applications. It helps in sending or retrieving information over servers asynchronously without hindering with the web page. This tutorial guides you on how to incorporate AJAX with Select2 plugin to create dynamic autocomplete search.

Select2 offer a customizable select box with profound support for creating a search, tag, remote data sets, infinite scrolling, not only but also many other highly exorbitant mnemonic options.

Create Laravel Project

Composer empowers Laravel to support its dependencies. So, configure the composer in your development system before working with Laravel.

Similarly, you may use the below command to install Laravel through your console:

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

Adding Database Details in ENV

Open .env configuration file, include database name, username and password:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=db
DB_USERNAME=root
DB_PASSWORD=

Configure Model & Migration

Create a database table using migration, so first create a model:

php artisan make:model Book -m

Put the code in database/migrations/create_books_table migration file:

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateBooksTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('books', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('books');
    }
}

Open app/Models/Book.php model file, replace with below code:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Book extends Model
{
    use HasFactory;
    protected $fillable = [
        'name'
    ];    
}

Evoke migration with given below command:

php artisan migrate

Insert Data in Database

For displaying results on the autocomplete search, you need to add some records in your database:

INSERT INTO `books` (`id`, `name`, `created_at`, `updated_at`) VALUES
(1, 'Anna Karenina', NULL, NULL),
(2, 'To Kill a Mockingbird', NULL, NULL),
(3, 'The Great Gatsby', NULL, NULL),
(4, 'One Hundred Years of Solitude', NULL, NULL),
(5, 'A Passage to India', NULL, NULL),
(6, 'Invisible Man', NULL, NULL),
(7, 'Don Quixote', NULL, NULL),
(8, 'Beloved', NULL, NULL),
(9, 'Mrs. Dalloway', NULL, NULL),
(10, 'Things Fall Apart', NULL, NULL);

Create Controller

Generate a new controller with below command:

php artisan make:controller AutocompleteController

Put the code in app\Http\Controllers\AutocompleteController.php file:

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Book;

class AutocompleteController extends Controller
{
    public function viewSearch()
    {
    	return view('welcome');
    }

    public function getBooks(Request $req)
    {
    	$books = [];

        if($req->has('q')){
            $search = $req->q;
            $books = Book::select("id", "name")
            		  ->where('name', 'LIKE', "%$search%")
            		  ->get();
        }
        return response()->json($books);
    }
}

Set up Routes

Import AutocompleteController at the top part after Route facades, next create two routes for showing and handling dynamic AJAX search.

Put code in routes/web.php file:

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\AutocompleteController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
*/

Route::get('/books', [AutocompleteController::class, 'viewSearch']);
Route::get('/search', [AutocompleteController::class, 'getBooks']);

Configure Blade View

We need a blade view where we can display the search bar, so first define a bootstrap link, thereafter also define the CSS and javascript links of select2 module.

Put the code in resources/views/welcome.blade.php:

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Laravel AJAX Autocomplete Example</title>

    <link rel="stylesheet" type="text/css"
        href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css" rel="stylesheet" />
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>

    <style>
        .container {
            max-width: 600px;
        }
    </style>

</head>

<body class="mt-5">
    <div class="container">
        <h2>Laravel AJAX Autocomplete Demo</h2>

        <select class="autosearch form-control" name="autosearch"></select>
    </div>
</body>

<script type="text/javascript">
    $('.autosearch').select2({
        placeholder: 'Select Books',
        ajax: {
            url: '/search',
            dataType: 'json',
            delay: 220,
            processResults: function (data) {
                return {
                    results: $.map(data, function (data) {
                        return {
                            text: data.name,
                            id: data.id
                        }
                    })
                };
            },
            cache: true
        }
    });
</script>
</html>

Laravel 8 Autocomplete Search Demo

You can start the application, to test the developed feature.

php artisan serve

Use the link to open the application:

http://127.0.0.1:8000/books

Thanks, the Laravel 8 Autocomplete tutorial is over.