Multi Select AutoComplete Search from Database with Eloquent ORM in Laravel Framework

Create new database named laravel_db. In this database, create new table named product as below:

  1. Download and install the latest version of Composer from https://getcomposer.org/download/

  2. Open Windows Terminal in Visual Studio Code install Laravel Installer with command as below:

    composer global require laravel/installer
  3. Create new folder named LearnLaravelWithRealApps. Use Visual Studio Code open to LearnLaravelWithRealApps foler. In this folder, create new project named LearnLaravelWithRealApps with command as below:

    laravel new LearnLaravelWithRealApps

  4. Run LearnLaravelWithRealApps project with command as below:

    php artisan serve
  5. Open LearnLaravelWithRealApps project with url as below:

    http://localhost:8000

Open .env file in root folder. Add values as below connect to database:

DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=laravel_db
DB_USERNAME=root
DB_PASSWORD=

Open Windows Terminal in Visual Studio Code and clear config cache with command as below:

php artisan config:clear

Create new PHP file named Product.php in app/Models folder as below:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    protected $primarykey = 'id';
    protected $table = 'product';
    public $timestamps = false;
}

Create new folder named Repositories. In Repositories folder, create new folder named Product. Create new PHP file named ProductRepository.php in app/Repositories/Product folder as below:

<?php

namespace App\Repositories\Product;

interface ProductRepository
{
    public function search($keyword);
}

Create new PHP file named ProductRepositoryImpl.php in app/Repositories/Product folder as below:

<?php

namespace App\Repositories\Product;

use App\Models\Product;

class ProductRepositoryImpl implements ProductRepository
{
    public function search($keyword)
    {
        return Product::where('name', 'like', '%'.$keyword.'%')->select('id', 'name')->get();
    }
}

Open AppServiceProvider.php file in app/Providers folder and add declare new repository to register method as below:

<?php

namespace App\Providers;

use App\Repositories\Product\ProductRepository;
use App\Repositories\Product\ProductRepositoryImpl;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this->app->bind(ProductRepository::class, ProductRepositoryImpl::class);
    }

    public function boot()
    {
    }
}

Create new PHP file named DemoController.php in app/Http/Controllers folder as below:

<?php

namespace App\Http\Controllers;

use App\Repositories\Product\ProductRepository;
use Illuminate\Http\Request;

class DemoController extends Controller
{
    protected $productRepository;

    public function __construct(ProductRepository $productRepository)
    {
        $this->productRepository = $productRepository;
    }

    public function index()
    {
        return view('demo/index');
    }

    public function search(Request $request)
    {
        $keyword = $request->get('term');
        return response()->json($this->productRepository->search($keyword));
    }
}

Create new folder named demo in resources/views folder. In this folder, create new Blade file named index.blade.php as below:

<html>

    <head>
        <title>Laravel</title>
        <style type="text/css">
            #autoCompletewithSelect2 {
                width: 600px;
            }
        </style>
        <link rel="stylesheet" href="//code.jquery.com/ui/1.13.0/themes/base/jquery-ui.css">
        <script src="https://code.jquery.com/jquery-3.6.0.js"></script>
        <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
        <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
        <script>
            $(document).ready(function() {
                $('#autoCompletewithSelect2').select2({
                    placeholder: 'Keyword...',
                    multiple: true,
                    ajax: {
                        type: 'GET',
                        url: "{{url('/demo/search')}}",
                        dataType: 'json',
                        processResults: function(data) {
                            return {
                                results: $.map(data, function(item) {
                                    return {
                                        text: item.name,
                                        id: item.id
                                    }
                                })
                            };
                        }
                    }
                });
            });
        </script>
    </head>

    <body>

        <h3>AutoComplete with Multiple Selection in Select2</h3>
        <select id="autoCompletewithSelect2" name="autoCompletewithSelect2" multiple="multiple"></select>

    </body>

</html>

Open web.php file in routes folder, add new routes as below:

<?php
    
use Illuminate\Support\Facades\Route;

use App\Http\Controllers\DemoController;

Route::get('/', [DemoController::class, 'index']);
Route::get('/demo', [DemoController::class, 'index']);
Route::get('/demo/index', [DemoController::class, 'index']);
Route::get('/demo/search', [DemoController::class, 'search']);

Access index action in Demo controller with urls as below:

  • http://localhost:8000
  • http://localhost:8000/demo
  • http://localhost:8000/demo/index

Output