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


Contents

  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/migration/ 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) {
       $table->bigIncrements('id');
       $table->string('name');
       $table->string('email');
       $table->timestamps();
    });
}
  • 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/[email protected]/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/[email protected]/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 $filliable property.

Completed Code

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Employees extends Model
{

   protected $fillable = [
     'name','email'
   ];

}

4. Route

  • Open routes/web.php file.
  • Define 2 routes –
Route::get('/','[email protected]');
Route::post('/employees/getEmployees/','[email protected]')->name('employees.getEmployees');
  • 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 in $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

<?php

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();
      }else{
         $employees = Employees::orderby('name','asc')->select('id','name')->where('name', 'like', '%' .$search . '%')->limit(5)->get();
      }

      $response = array();
      foreach($employees as $employee){
         $response[] = array(
              "id"=>$employee->id,
              "text"=>$employee->name
         );
      }

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

6. View

Create file –

  • Create a new folderemployees at resources/views/ folder.
  • In resources/views/employees/ directory 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>
<html>
  <head>
    <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>

  </head>
  <body>

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

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

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

      $( "#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
        }

      });

    });
    </script>
  </body>
</html>

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.
Are you want to get implementation help, or modify or extend the functionality of this script? Submit paid service request.

6 thoughts on “Loading data remotely in Select2 – Laravel 7”

  1. Hi!! Thanks for your guide!!
    I followed it but when I type into the select2, nothing happens.
    I also looked into the network tab of Firefox development tool but no calls have been done…
    Could you help me please?

    Reply
  2. One way to make the controller even cleaner can be by changing the method to:
    { [Pt-BR] Uma forma de deixar o Controller ainda mais enxuto seria utilizando assim: }

    public function getEmployees(Request $request){
    $categories = Employees::orderBy(‘description’, ‘asc’)->select(‘id’, ‘name as text’);
    $search = $request->get(‘search’);
    $search == ” ?: $employees->where(‘name’, ‘like’, ‘%’ . $search . ‘%’);

    return response()->json($employees->limit(5)->get());
    }

    Reply
  3. I am getting Json response in browser network but not getting any data object into console.log

    $(‘select[name=”college[]”]’).select2({
    ajax: {
    url: ‘{{ url(“/getUnivercityListAjax”) }}’,
    type: “GET”,
    dataType: ‘json’,
    delay: 250,
    data: function (params) {
    return {
    name: params.term // search term
    };
    },
    success : function (data) {

    return {
    results: $.map(data, function(obj) {
    return { id: obj.id, text: obj.name };
    })
    };
    },
    cache: true
    }

    });

    }

    Reply
  4. [{“id”:2592,”name”:”Oxford Brookes University”,”description”:”Oxford Brookes University”,”is_deleted”:0,”created_by”:1,”updated_by”:1,”created_at”:”26\/12\/2019 09:54:18″,”updated_at”:”26\/12\/2019 09:54:18″},{“id”:2664,”name”:”University of Oxford”,”description”:”University of Oxford”,”is_deleted”:0,”created_by”:1,”updated_by”:1,”created_at”:”26\/12\/2019 09:54:20″,”updated_at”:”26\/12\/2019 09:54:20″}]

    Reply
  5. Thank you for this. However, when I try to save the selected item to the database, all I get is the ID and not the Text. How can I get the Text to save to the database and not the ID?

    Reply

Leave a Comment