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:


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:


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) {

     * Reverse the migrations.
     * @return void
    public function down()

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


namespace App\Models;

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

class Book extends Model
    use HasFactory;
    protected $fillable = [

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:


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 = [];

            $search = $req->q;
            $books = Book::select("id", "name")
            		  ->where('name', 'LIKE', "%$search%")
        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:


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()) }}">

    <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"
    <script src=""></script>
    <link href="[email protected]/dist/css/select2.min.css" rel="stylesheet" />
    <script src="[email protected]/dist/js/select2.min.js"></script>

        .container {
            max-width: 600px;


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

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

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

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:

Thanks, the Laravel 8 Autocomplete tutorial is over.