Laravel Javascript

Laravel Autocomplete Search with Select2 JS Example

The following code is an example of how to implement autocomplete search functionality with Select2 JavaScript library in Laravel:

1. Install Laravel by running the following command:

composer create-project laravel/laravel example-app

2. Set up the database and run migrations to create tables:

php artisan migrate

3. Generate dummy data using factory:

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

4. Define routes in `routes/web.php`:

use App\Http\Controllers\FunctionController;
Route::get('/select2', function () {
   return view('select2');
});
Route::get('customers-list', [FunctionController::class, 'user_list'])->name('user.list');

5. Create a new controller `FunctionController.php` in the `app/Http/Controllers` directory:

<?php
namespace App\Http\Controllers;
use App\Models\User;
use App\Http\Controllers\Controller;
class FunctionController extends Controller
{
   public function user_list($selected_id = [])
   {
       $per_page = 50;
       $search = request()->q;
       $items = User::when($search, function ($query) use ($search) {
           return $query->where(function ($query) use ($search) {
               $query->where('name', 'like', '%' . $search . '%')->orWhere('email', 'LIKE', "%$search%");
           });
       })
       ->when($selected_id, function ($query) use ($selected_id) {
           if (!empty($selected_id)) {
               return $query->whereIn('id', $selected_id);
           }
       })
       ->select("id", "name", "email")->paginate($per_page);
       foreach ($items as $item) {
           $avatars_image = "https://eu.ui-avatars.com/api/?length=1&name={$item->name[0]}";
           $item->text = $item->name;
           $item->image = ($item->image ?? $avatars_image);
           $item->description = $item->email;
       }
       if (request()->ajax()) {
           return response()->json($items);
       }
       $output = '';
       $output .= "<option value=''>Select Users</option>";
       foreach ($items as $item) {
           if (in_array($item->id, $selected_id)) {
               $selected = 'selected=""';
           } else {
               $selected = "";
           }
           $output .= "<option " . $selected . " value='" . $item->id . "'>" . $item->name . "</option>";
       }
       return $output;
   }
}

6. Create a new view file `select2.blade.php` in the `resources/views` directory:

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Bootstrap Example</title>
   <meta charset="utf-8">
   <meta name="viewport" content="width=device-width, initial-scale=1">
   <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
   <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
   <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
   <style>
       /* CSS styles for Select2 */
       /* ... */
   </style>
</head>
<body>
   <div class="container mt-3">
       <h2>Select2 form</h2>
       <form action="{{ url('select2') }}">
           <div class="mb-3">
               <label for="singel_user" class="form-label">Single User:</label>
               <select name="singel_user" class="javascript-select-list-data" data-ajax--url="{{ route('user.list') }}">
                   {!! (new App\Http\Controllers\FunctionController())->user_list([request()->singel_user]) !!}
               </select>
           </div>
           <div class="mb-3">
               <label for="multiple_user" class="form-label">Multiple Users:</label>
               <select name="multiple_user[]" multiple class="javascript-select-list-data" data-ajax--url="{{ route('user.list') }}">
                   {!! (new App\Http\Controllers\FunctionController())->user_list((request()->multiple_user ?? [])) !!}
               </select>
           </div>
           <button type="submit" class="btn btn-primary">Submit</button>
       </form>
   </div>
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
   <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
   <script>
       // Initialize Select2
       $(".javascript-select-list-data").select2({
           width: '100%',
           ajax: {
               dataType: 'json',
               delay: 250,
               data: function (params) {
                   return {
                       q: params.term,
                       page: params.page
                   };
               },
               processResults: function (data, params) {
                   params.page = params.page || 1;
                   return {
                       results: $.map(data.data, function (item) {
                           return {
                               text: item.text,
                               id: item.id,
                               image: item.image,
                               description: item.description
                           }
                       }),
                       pagination: {
                           more: (params.page * 10) < data.total
                       }
                   };
               },
               cache: true
           },
           placeholder: 'Search Data',
           minimumInputLength: 0,
           templateResult: formatRepo,
           templateSelection: formatRepoSelection
       });
       // Format the displayed result in Select2
       function formatRepo(repo) {
           if (repo.loading) {
               return repo.text;
           }
           var $container = $(
               "<div class='select2-result-repository clearfix'>" +
               "<div class='select2-result-repository__avatar'><img src='" + repo.image + "' /></div>" +
               "<div class='select2-result-repository__meta'>" +
               "<div class='select2-result-repository__title'></div>" +
               "<div class='select2-result-repository__statistics'>" +
               "<div class='select2-result-repository__forks'></div>" +
               "</div>" +
               "</div>" +
               "</div>"
           );
           $container.find(".select2-result-repository__title").text(repo.text);
           $container.find(".select2-result-repository__forks").append(repo.description);
           return $container;
       }
       function formatRepoSelection(repo) {
           return repo.text || repo.text;
       }
   </script>
</body>
</html>


Start the development server by running the following command:

php artisan serve

Access the example page in your web browser using the URL:

http://localhost:8000/select2

This example demonstrates how to create an autocomplete search feature using the Select2 library in Laravel . The provided code sets up the necessary routes, controller, and view to display a form with two Select2 inputs for single and multiple user selection. The user data is fetched from the database and paginated. Select2 handles the search functionality and displays the results with avatars and descriptions.

Make sure to have the required dependencies installed and adjust the code according to your specific needs and database setup.

Leave A Comment