Skip to content
Readerstacks logo Readerstacks
  • Home
  • Softwares
  • Angular
  • Php
  • Laravel
  • Flutter
Readerstacks logo
Readerstacks
Laravel Multi Select Tag Autocomplete Using Select2

Laravel Multi Select Tag Autocomplete Using Select2

Aman Jain, July 19, 2022July 19, 2022

In this article we will learn to use Laravel Multi Select Tag Autocomplete Using Select2. Select2 is useful when we want live search of bulk data or to convert the existing select boz with multi features like search, multi select and options customizations. In this article we will cover multiple tagging or selection like Gmail, Outlook and will populate the suggestion based on typing. Autocomplete search is mostly work of javascript and when we want to fetch live data from database then we require the intervention of laravel to provide the data in JSON response.

Select2 library is completely build for achieve the autocomplete suggestion functionality in the application with robust features of it. We will customize the options list in the article with html data.

In this example we will create a simple select box to search on type and give a list suggestion based on typed term. then in laravel we will create an API to response the result of search. we can even customize the pagination, markup, selection option in the select2.

This example will work with any version of laravel like laravel 5, laravel 6, laravel 7, laravel 8 and laravel 9 too.

Let start the simple tutorial of Laravel Ajax Autocomplete Using Select2 step by step

Step 1: Create a laravel project

First step is to create the Laravel project using composer command or you can also read the How to install laravel 8 ? and Laravel artisan command to generate controllers, Model, Components and Migrations

composer create-project laravel/laravel crud

Step 2: Configure database

Next step is to configure the database for our project, table and data. So open .env or if file not exist then rename .env.example file to .env file in root folder and change below details

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

Step 3: Create Model and Migration

If you have table and large data already then you can skip this step but if you are beginner and trying to implement autosuggestion then in this step we are creating a model and migration using artisan command

php artisan make:model User -m

Step 4 : Create a controller

Next, Create a controller and two methods one for view and another for search the suggestion as follow

php artisan make:controller UserController

Now, add the controller logic

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class UserController extends Controller
{
    function index(){
        return view("users.search");
    }
    function search(Request $request){

        return  \App\Models\User::where("email","like","%{$request->term}%")
        ->select("id","email","name")
        ->limit(10)
        ->get();
    }
}

Here we created two methods index for show the view and search method for response the related users list according to keyword.

Step 5 : Create the view

Now, create a view file named as resources/views/users/search.blade.php and put the follow code

<!DOCTYPE html>
<html>

<head>
  <title>Laravel Multi Select Tag Autocomplete Using Select2 - readerstacks.com</title>

</head>

<body>
  <div class="container">

    <div class="panel panel-primary">
      <div class="panel-heading">
        <h2>Laravel Multi Select Tag Autocomplete Using Select2 -readerstacks.com</h2>
      </div>
      <div class="panel-body">

        <div class="col-md-4">
          <label>Title</label>
          <select type="text" multiple placeholder="Users" name="users" id='users' class="form-control">
          </select>
        </div>

      </div>
    </div>
  </div>
</body>

</html>

<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-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>
<script type="text/javascript">
  var route = "{{url('users/search')}}";
  

  $('#users').select2({

    placeholder: 'Select User',

    escapeMarkup: function(markup) { 
          return markup;
    },
    templateResult: function(data) {
       
      return data.html;
    },
    templateSelection: function(data) {
      

      if (data && !data.selected) 
      return data.text;
    },
    ajax: {
      url: route,
      dataType: 'json',
      delay: 250,
      processResults: function(data) {
        return {
          results: $.map(data, function(item) {
            return {
              html:"<span>"+item.name+"</span><br><span style='color:red'>"+item.email+"</span>",
              text: item.name,
              id: item.id
            }
          })
        };
      },
      cache: true,

    }
  });
</script>

Now, here we imported the jQuery and select2.min.js and CSS to implement the suggestion list autocomplete

Majorly we created templateResult to show the html key in result option, templateResult key to set the value on select of option and escapeMarkup to escaping the markups.

Step 6 : Create Route

Last and final step is to create the route for our implementation

<?php

use Illuminate\Support\Facades\Route;

Route::get('/users',"\App\Http\Controllers\UserController@index");
Route::get('/users/search',"\App\Http\Controllers\UserController@search");

Live Screenshot :

Laravel Multi Select Tag Autocomplete Using Select2 - readerstacks.com
Laravel Multi Select Tag Autocomplete Using Select2 – readerstacks.com

Related

Javascript jQuery Laravel Laravel 9 Php ajaxautocompletecustomizedlaravelmultipleSELECT2suggestion list

Post navigation

Previous post
Next post

Related Posts

Javascript Angular Select Change Event Example

Angular Select Change Event Example

September 23, 2022March 16, 2024

Angular Select Change Event is an angular event binding it triggers when user change the value of select box and it fires a event of (change). Select events in angular can be handled using input and output decorators and in this tutorial we will learn Angular change Event on select…

Read More
Php How to use conditional validation Laravel 8

How to use conditional validation Laravel 8 / 9 ?

December 17, 2021March 19, 2022

In Laravel sometime you want to exclude some validations on specific condition. Laravel provides exclude_if, exclude_unless and sometimes validation rules to validating some rules conditionally. In this tutorial we will take a simple example of has_city is checked then city name should be require and if its not checked then…

Read More
Javascript How to use local storage in angular

How to use local storage in angular ?

April 18, 2022October 4, 2022

Local storage are used to store client side data in browser and in this tutorial we will learn to use local storage in angular. Angular is a javascript framework and used to enable to seamless developer experience to build web and mobile applications. Local storage are useful when we want…

Read More

Aman Jain
Aman Jain

With years of hands-on experience in the realm of web and mobile development, they have honed their skills in various technologies, including Laravel, PHP CodeIgniter, mobile app development, web app development, Flutter, React, JavaScript, Angular, Devops and so much more. Their proficiency extends to building robust REST APIs, AWS Code scaling, and optimization, ensuring that your applications run seamlessly on the cloud.

Categories

  • Angular
  • CSS
  • Dart
  • Devops
  • Flutter
  • HTML
  • Javascript
  • jQuery
  • Laravel
  • Laravel 10
  • Laravel 11
  • Laravel 9
  • Mysql
  • Php
  • Softwares
  • Ubuntu
  • Uncategorized

Archives

  • July 2025
  • June 2025
  • May 2025
  • April 2025
  • October 2024
  • July 2024
  • February 2024
  • January 2024
  • December 2023
  • November 2023
  • October 2023
  • July 2023
  • March 2023
  • November 2022
  • October 2022
  • September 2022
  • August 2022
  • July 2022
  • June 2022
  • May 2022
  • April 2022
  • March 2022
  • February 2022
  • January 2022
  • December 2021
  • November 2021
  • October 2021
  • September 2021
  • August 2021
  • July 2021
  • June 2021

Recent Posts

  • Mapping Together: The Vibrant Spirit of OpenStreetMap Japan
  • Understanding High Vulnerabilities: A Deep Dive into the Weekly Summary
  • Building a Million-Dollar Brand: The Journey of Justin Jackson
  • Mastering Schedule Management with Laravel Zap
  • The Resilience of Nature: How Forests Recover After Fires
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version