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.

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/ directory from the project root.
  • Find a PHP file which 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 jQuery library in public/ directory.

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 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 in id key and $employee->name in 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 ); } echo json_encode($response); exit; }

6. View

Create file –

  • Create a new directory employees at resources/views/ directory.
  • 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 in 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</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.4.1.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>

7. 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 which has id and text key from the controller.

Related Posts