Laravel 10 Select2 Autocomplete Search Using Ajax

Websolutionstuff | Apr-10-2023 | Categories : Laravel PHP jQuery MySQL

In this article, we will see laravel 10 select2 autocomplete search using ajax. Here, we will learn about select2 autocomplete search using ajax in laravel 10. You can search records from the database without page refresh or without form submission. Also, you can customize your search as per your requirements.

So, let's see how to autocomplete search using ajax in select2, select2 ajax laravel 10, select2 autocomplete ajax, and how to use select2 in laravel 10.

Select2 gives you a customizable select box with support for searching, tagging, remote data sets, infinite scrolling, and many other highly used options. In order to use Select2, you must include the compiled JavaScript and CSS files on your website.

Using Select2 from a CDN:

A CDN (content delivery network) is the fastest way to get up and running with Select2. Select2 is hosted on both the jsDelivr and cdnjs CDNs. Simply include the following lines of code in the <head> section of your page.

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

 

Step 1: Install Laravel 10

In this step, we will install laravel 10 using the following command. So, run the below code to the terminal.

composer create-project laravel/laravel laravel_10_select2_search_example

 

Step 2: Add Dummy Users

Then we will run default migration using the following command. So, run the below code to the terminal.

php artisan migrate

After that, we will create dummy records using the tinker.

php artisan tinker
  
User::factory()->count(50)->create();

 

 

Step 3: Create Controller

Now, we will create UserController using the following command. And add the two methods. So, add the following code to that file.

php artisan make:controller UserController

app/Http/Controllers/UserController.php

<?php
    
namespace App\Http\Controllers;
   
use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\View\View;
use Illuminate\Http\JsonResponse;
    
class UserController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(): View
    {
        return view('index');
    }
      
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function autoCompleteSearch(Request $request): JsonResponse
    {
        $data = [];
    
        if($request->filled('q')){
            $data = User::select("name", "id")
                        ->where('name', 'LIKE', '%'. $request->get('q'). '%')
                        ->get();
        }
     
        return response()->json($data);
    }
}
 
Step 4: Create Routes

Then we will create routes to the web.php file. So, add the following code to that file.

routes/web.php

<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\UserController;
  
/* 
|--------------------------------------------------------------------------
| 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::controller(UserController::class)->group(function(){
    Route::get('index', 'index');
    Route::get('auto-complete-search', 'autoCompleteSearch')->name('autocompletesearch');
});

 

Step 5: Create View File

Now, we will create an index.blade.php file. So, add the following HTML to that file.

resources/views/index.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Laravel 10 Select2 Autocomplete Search Using AJAX - Websolutionstuff</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css"/>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js"></script>
</head>
<body>
     
<div class="container">
    <h4 class="mt-5 mb-4">Laravel 10 Select2 Autocomplete Search Using AJAX - Websolutionstuff</h4>   
    <select class="form-control" id="search" style="width:780px;" name="user_id"></select>
</div>
     
<script type="text/javascript">
    var path = "{{ route('autocompletesearch') }}";
  
    $('#search').select2({
        placeholder: 'Search Records',
        ajax: {
          url: path,
          dataType: 'json',
          delay: 250,
          processResults: function (data) {
            return {
              results:  $.map(data, function (item) {
                    return {
                        text: item.name,
                        id: item.id
                    }
                })
            };
          },
          cache: true
        }
      });
  
</script>
     
</body>
</html>

Output: 

laravel_10_select2_autocomplete_search_using_ajax_output

 


You might also like:

Recommended Post
Featured Post
How To Push Array Element In Node.js
How To Push Array Element In N...

Hello Dev, In this example we will see how to push array element in node.js example. I will share some example about&...

Read More

Oct-11-2021

How To File Upload With Progress Bar Angular 15
How To File Upload With Progre...

In this article, we will explore how to implement a file upload feature in Angular 15 with a progress bar. We will guide...

Read More

Jun-23-2023

Laravel 8 User Roles and Permissions Without Package
Laravel 8 User Roles and Permi...

In this tutorial we will see laravel 8 user roles and permissions without package.Roles and permissions are an impo...

Read More

Sep-13-2021

How to Install PHP PDO MySQL Extension in Ubuntu 22.04
How to Install PHP PDO MySQL E...

Hey there! If you're diving into PHP development on Ubuntu 22.04 and need to connect your applications to MySQL data...

Read More

Feb-28-2024