Laravel 7|8 Dynamic Autocomplete Search with Select2 Example

Last updated on by Digamber
This is a comprehensive laravel post; in this tutorial, we will look at how to build a dynamic autocomplete search using the Select2 jQuery plugin in Laravel 7 with AJAX.

Let me give you an overview of how we will proceed. We will install a new laravel application, make the database connection and pour some fake movies data into it. Afterward, we will create a model and a controller and bind it to view. Lastly, i will create a view and relentlessly add Bootstrap 5 and implement Select2 JavaScript CDN link to create an autocomplete search.

Install Laravel Application

First and foremost step begins with installing the brand new laravel application. Run the command to sustain the development process.

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

Next, get into the project directory:

cd laravel-autocomplete-search

Skip this step, if you have already installed the app.

Configure Database

Add database name, username and password in .env file; it sustains the consensus between laravel and database.

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

MAMP user may get given below error while running the migration. Incorporate the following code after the database configuration in .env file.

DB_HOST=localhost;unix_socket=/Applications/MAMP/tmp/mysql/mysql.sock

Add some fake data that needs to be searched, go to PHPMyAdmin and run the following SQL query.

INSERT INTO `movies` (`id`, `name`, `created_at`, `updated_at`) VALUES
(1, 'Black Panther', NULL, NULL),
(2, 'Avengers: Endgame', NULL, NULL),
(3, 'Mission: Impossible - Fallout', NULL, NULL),
(4, 'Spider-Man: Into the Spider-Verse', NULL, NULL),
(5, 'Mad Max: Fury Road', NULL, NULL),
(6, 'Wonder Woman', NULL, NULL),
(7, 'Coco', NULL, NULL),
(8, 'Dunkirk', NULL, NULL),
(9, 'Thor: Ragnarok', NULL, NULL),
(10, 'Logan', NULL, NULL);

Model & Migration

Create a Movie Model that is generated by the following model command.

php artisan make:model Movie -m

In database/migrations/timestamp_create_movies_table file add the table values that you want to generate in database.

<?php

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

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

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

Create the app/Movie.php and add the given values within the $fillable array.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Movie extends Model
{
    protected $fillable = [
        'name'
    ];
}

Run the following command to run the migration.

php artisan migrate

Create Routes

We need to create two routes. Both the routes simultaneously load the search view and process AJAX dynamic search through select2 jQuery plugin to fetch the data from the database and display it to the user.

Add the below code in routes/web.php file.

<?php

use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('search', 'Select2SearchController@index');
Route::get('ajax-autocomplete-search', 'Select2SearchController@selectSearch');

Create Autocomplete Search Controller

Create a controller by using the following command.

php artisan make:controller Select2SearchController

In controller file we will create two functions.

The index() method brings the autocomplete search in the view, and the selectSearch() function contains the logic to fetch the data from the database on matched text.

Insert the following code in Select2SearchController.php.

<?php

namespace App\Http\Controllers;
use App\Movie;
use Illuminate\Http\Request;

class Select2SearchController extends Controller
{

    public function index()
    {
    	return view('home');
    }

    public function selectSearch(Request $request)
    {
    	$movies = [];

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

Create View

Theoretically, we have reached almost the last step of this tutorial. First, create resources/views/home.blade.php file, then add the following code.

<!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 Dynamic Search with select2</title>

    <link rel="stylesheet" type="text/css"
        href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.0.0-alpha1/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/select2@4.1.0-beta.1/dist/css/select2.min.css" rel="stylesheet" />
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-beta.1/dist/js/select2.min.js"></script>

    <style>
        .container {
            max-width: 500px;
        }
        h2 {
            color: white;
        }
    </style>

</head>

<body class="bg-primary">
    <div class="container mt-5">
        <h2>Laravel AJAX Autocomplete Search with Select2</h2>

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

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

We import the Bootstrap 5 beta version to use the custom UI component to spruce up the UI. We are also implementing the select2 jQuery plugin CDN link inside the head part of the template.

Test App

Finally, we have gone through each and every imperative respectively. Now, Its time to test out what we have built.

Run the following command to start the laravel app.

php artisan serve

Open the following URL in the browser:

http://127.0.0.1:8000/search

Laravel 7 Dynamic Autocomplete Search with Select2 Example

Download the full code of this tutorial from GitHub.