Loading data remotely in Select2 – Laravel 7

Select2 is a jQuery plugin which customize <select > element and adds multiple functionality like – searching, multiple option selections, etc.

You can import data using jQuery AJAX or directly list data in the element.

In this tutorial, I show how you can add select2 on a select element and load data using jQuery AJAX in the Laravel 7 project.

Loading data remotely in Select2 – Laravel 7


  1. Create Table
  2. Download
  3. Model
  4. Route
  5. Controller
  6. View
  7. Demo
  8. Conclusion

1. Create Table

  • Create a new table Employees using migration and add some records.
php artisan make:migration create_employees_table
  • Now, navigate to database/migrations/ folder from the project root.
  • Find a PHP file that ends with create_employees_table and open it.
  • Define the table structure in the up() method.
public function up()
    Schema::create('employees', function (Blueprint $table) {
  • Run the migration –
php artisan migrate
  • The table is been created and add some records in it.

2. Download

  • Download Select2 library from GitHub and also download the jQuery library.
  • Extract the downloaded files in public/ directory.
  • Also, copied the jQuery library in public/ directory.
  • You can also use CDN –
<!-- CSS -->
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />

<!-- Script -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

3. Model

  • Create Employees Model.
php artisan make:model Employees
  • Specify mass assignable Model attributes – name, and email using the $fillable property.

Completed Code


namespace App;

use Illuminate\Database\Eloquent\Model;

class Employees extends Model

   protected $fillable = [


4. Route

  • Open routes/web.php file.
  • Define 2 routes –
  • The 2nd route is used for AJAX request.

5. Controller

  • Create EmployeesController Controller.
php artisan make:controller EmployeesController
  • Open app/Http/Controllers/EmployeesController.php file.
  • Import Employees Model.
  • Create two methods –
    • index() – Load employees.index view.
    • getEmployees() – This use to handle AJAX request. Read POST search value and assign to $search.

If $search is empty then select the first 5 records from the employees table otherwise use $search in where on the name field and select the first 5 records.

Loop on the fetched records. Pass $employee->id to id key and $employee->name to text key.

Return $response Array in JSON format.

Completed Code


namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Employees;

class EmployeesController extends Controller{

   public function index(){
      return view('employees.index');

   AJAX request
   public function getEmployees(Request $request){

      $search = $request->search;

      if($search == ''){
         $employees = Employees::orderby('name','asc')->select('id','name')->limit(5)->get();
         $employees = Employees::orderby('name','asc')->select('id','name')->where('name', 'like', '%' .$search . '%')->limit(5)->get();

      $response = array();
      foreach($employees as $employee){
         $response[] = array(

      return response()->json($response);

6. View

Create file –

  • Create a new folderemployees at resources/views/ folder.
  • In resources/views/employees/ folder create a new index.blade.php file.

Include CSS and JS –

  • Specify csrf_token() in the <meta >.
  • Include Select2 CSS, jQuery and Select2 JS files at the <head > section.

Select fields –

  • Create a <select id='selUser'>.

Script –

  • Read csrf_token from meta tag and assign to CSRF_TOKEN variable.
  • Initialize select2 on #selUser field.
  • Using ajax option to send AJAX post request to route('employees.getEmployees') to fetch employees list for displaying.
  • Also, pass CSRF_TOKEN along with search value as data.
  • Handle AJAX response with processResults. Initialize results with the response.

Completed Code

<!DOCTYPE html>
    <title>Loading data remotely in Select2 – Laravel 7</title>

    <!-- Meta -->
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta charset="utf-8">
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <!-- CSS -->
    <link rel="stylesheet" type="text/css" href="{{asset('select2/dist/css/select2.min.css')}}">

    <!-- Script -->
    <script src="{{asset('jquery-3.6.0.min.js')}}" type="text/javascript"></script>
    <script src="{{asset('select2/dist/js/select2.min.js')}}" type="text/javascript"></script>


    <!-- For defining autocomplete -->
    <select id='selUser' style='width: 200px;'>
      <option value='0'>-- Select user --</option>

    <!-- Script -->
    <script type="text/javascript">

    // CSRF Token
    var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');

      $( "#selUser" ).select2({
        ajax: { 
          url: "{{route('employees.getEmployees')}}",
          type: "post",
          dataType: 'json',
          delay: 250,
          data: function (params) {
            return {
              _token: CSRF_TOKEN,
              search: params.term // search term
          processResults: function (response) {
            return {
              results: response
          cache: true



7. Demo

View Demo

8. Conclusion

You can also use GET request to send AJAX request but you need to update the route to GET.

Fetch records and return an Array that has id and text key from the controller.

You can view the Laravel 8 version of this tutorial here.

If you found this tutorial helpful then don't forget to share.