Did you know that we can create laravel autocomplete search ajax using select2 jQuery plugins? Yes, we can create select2 ajax search example in Laravel 9 application. In this tutorial, we will see how to load data using jQuery ajax in select2 laravel 9.

We will search user's data from the database using select2 using an ajax request. So, to create this dynamic autocomplete in laravel, we will use select2 jQuery plugins. There are also options to add pagination in search result of select2 plugins. 

You can see the preview example demo of this tutorial that we are going to make

laravel-9-select2-autocomplete-search-example

So let's see the source code of loading data remotely in select2 with ajax in laravel.

Step 1: Download Fresh Laravel

In this first step, we need a fresh Laravel 9 application for the how to load data using jQuery ajax in select2 laravel 9 tutorial. So download it by the below command:

composer create-project laravel/laravel example-app

 

Step 2:  Create Route

Now in this, create a resource route like the one below to complete the laravel select2 ajax pagination. So define the resource route like the below:

routes/web.php

<?php

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


Route::get('/user', [TutorialController::class,'index']);
Route::get('get_user', [TutorialController::class,'get_user'])->name('get_user');

 

Read also:  Laravel 9 CRUD Tutorial Using Query Builder

 

Step 3: Create Controller

Now in this step, we have to create a TutorialController to define this method to create a select2 ajax laravel.

php artisan make:controller TutorialController

 

Now update the controller like the below:

app/Http/Controllers/TutorialController.php

<?php

namespace App\Http\Controllers;

use App\Models\User;

class TutorialController extends Controller
{   
    public function index()
    {
        return view('welcome');
    }
    
    public function get_user()
    {
        $users = User::select("name", "id")
                    ->where('name', 'LIKE', '%'. request()->get('q'). '%')
                    ->get();
                    
        return response()->json($users);
    }
}

 

Step 4: Create Views

We are almost there. Just we have to create welcome.blade.php completing how to load data using jQuery ajax in select2 laravel 9.So create these files inside the following path and update them like below:

resources/views/welcome.blade.php

@extends('layouts.app')

@push('style')
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<style>
    span.select2.select2-container.select2-container--classic{
        width: 100% !important;
    }
</style>
@endpush

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header" style="background: gray; color:#f1f7fa; font-weight:bold;">
                    Laravel 9 Multi Select Dropdown With Ajax Search Example  -  Laravelia
                </div>
                 <div class="card-body">                    
                    <form class="w-px-500 p-3 p-md-3" action="{{ route('user.store') }}" method="post" enctype="multipart/form-data">
                        @csrf
                        <div class="row mb-3">
                            <label class="col-sm-3 col-form-label">Framework</label>
                            <div class="col-sm-9 mt-3">
                                <select class="js-example-basic-single" multiple name="Framework[]">
                                    {{-- <option value="CakePHP">Cake PHP</option>
                                    <option value="Laravel">Laravel</option>
                                    <option value="Symphony">Symphony</option> --}}
                                </select>
                            </div>
                        </div>

                        <div class="row mb-3">
                            <label class="col-sm-3 col-form-label"></label>
                            <div class="col-sm-9">
                                <button type="submit" class="btn btn-success btn-block text-white">Submit</button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

@push('script')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script>
$(document).ready(function(){
    $('.js-example-basic-single').select2({
        theme: "classic",
        placeholder: 'Search users',
        minimumInputLength: 2,
        ajax: {
          url: "{{ route('get_user') }}",
          dataType: 'json',
          delay: 250,
          processResults: function (data) {
            return {
                results: $.map(data, function (item) {
                    return {
                        text: item.name,
                        id: item.id
                    }
                })
            };
          },
          cache: true
        }
    });
});
</script>
@endpush

 

Now if you submit this form, we will see the following output:

{
  "_token": "cE3FdeFl8WSPpctD2fjXjJ24qcdhWvlPtV7qcrsT",
  "Framework": [
    "4",
    "49",
    "56"
  ]
}

 

Read also: How To Get Multiple Selected Values Of Select Box In Laravel

 

Conclusion

Hope this select2 ajax search example tutorial will help. After completing this select2 ajax, your concept will be clear about select2 ajax laravel. Hope this how to load data using jQuery ajax in select2 laravel 9 tutorial will clear your concept about laravel select2 ajax pagination.