Laravel 8 Load Data using jQuery AJAX in Select2

Share this Article
Reading Time: 7 minutes

Inside this article we will use the concept of select2 jquery plugin to load dynamic data using ajax in Laravel 8.

select2 is a jquery plugin which alters HTML element and create dynamic element with ajax data. This tutorial will cover all easy steps to integrate and implement this functionality.

Learn More –

We will see the concept of Laravel 8 load data using jquery Ajax in select2. This tutorial will use a complete basic idea to learn as well as to integrate in a very easy way. This will use select2 which binds autocomplete data set.

Let’s get started.

Installation of Laravel Application

Laravel Installation can be done in two ways.

  • Laravel Installer
  • By using composer

Laravel Installer

To install Laravel via Laravel installer, we need to install it’s installer first. We need to make use of composer for that.

$ composer global require laravel/installer

This command will install laravel installer at system. This installation is at global scope, so you type command from any directory at terminal. To verify type the given command –

$ laravel

This command will open a command palette of Laravel Installer.

To create ad install laravel project in system,

$ laravel new blog

With the name of blog a laravel project will be created at your specified path.

By using composer

Alternatively, we can also install Laravel by Composer command create-project.

If your system doesn’t has composer Installed, Learn Composer Installation Steps.

Here is the complete command to create a laravel project-

$ composer create-project --prefer-dist laravel/laravel blog

After following these steps we can install a Laravel application into system.

To start the development server of Laravel –

$ php artisan serve

This command outputs –

Starting Laravel development server:

Assuming laravel already installed at system.

Create Database & Connect

To create a database, either we can create via Manual tool of PhpMyadmin or by means of a mysql command.

CREATE DATABASE laravel_app;

To connect database with application, Open .env file from application root. Search for DB_ and update your details.


Create Model and Migrations

Open project into terminal and run this command.

$ php artisan make:model Country -m

It will create two files –

  • Model file Country.php at /app/Models folder.
  • Migration file 2021_06_27_151155_create_countries_table.php at /database/migrations folder.

Open Migration file 2021_06_27_151155_create_countries_table.php and write this complete code into it.


use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateCountriesTable extends Migration
     * Run the migrations.
     * @return void
    public function up()
        Schema::create('countries', function (Blueprint $table) {
            $table->char("iso", 2);
            $table->string("name", 50);
            $table->string("nicename", 50);
            $table->char("iso3", 3)->nullable();

     * Reverse the migrations.
     * @return void
    public function down()

Open Country.php model file and write this complete code into it.


namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Country extends Model
    use HasFactory;

    public $timestamps = false;

Run Migration

Back to terminal and run this command to run migration and create table.

$ php artisan migrate

It will run all migrations.

Insert Data into Table

As from migration we have created a table named as countries. We need some data into this table to test autocomplete search.

For data here we have the link of github.

Run the given mysql query to your database from this github link.

When you will run, you will get data something like this.

Create Controller

Back to terminal and run this command to create controller file.

$ php artisan make:controller SearchController

It will create SearchController.php file inside /app/Http/Controllers folder.


namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Country;

class SearchController extends Controller
     * Display a listing of the resource.
     * @return \Illuminate\Http\Response
    public function index()
        return view('search');

     * Show the form for creating a new resource.
     * @return \Illuminate\Http\Response
    public function getCountries(Request $request)
        $input = $request->all();

        if (!empty($input['query'])) {

            $data = Country::select(["id", "nicename"])
                ->where("nicename", "LIKE", "%{$input['query']}%")
        } else {

            $data = Country::select(["id", "nicename"])

        $countries = [];

        if (count($data) > 0) {

            foreach ($data as $country) {
                $countries[] = array(
                    "id" => $country->id,
                    "text" => $country->nicename,
        return response()->json($countries);

Add Routes

Open web.php file from /routes folder. Add these given routes into it.


use App\Http\Controllers\SearchController;

Route::get('data', [SearchController::class, 'index'])->name('search');
Route::post('countries', [SearchController::class, 'getCountries'])->name('countries');


Download Select2 CDN

  • Download the select2 plugin from here.
  • Extract it in the public/ folder at the root.
<link href="" rel="stylesheet" />

<script src=""></script>

Create Blade Layout File

Create search.blade.php file inside /resources/views folder.

Open search.blade.php and write this complete code into it.

<!DOCTYPE html>


    <title>How to Load data using jQuery AJAX in Select2 – Laravel 8</title>

    <link rel="stylesheet" href="">

    <!-- jQuery -->
    <script src=""></script>

    <link href="" rel="stylesheet" />

    <script src=""></script>


    <div class="container" style="margin-top: 40px;">
        <div class="panel panel-primary">
            <div class="panel-heading">Laravel 8 Load Data using jQuery AJAX in Select2</div>
            <div class="panel-body">
                    <label>Select Country</label>
                <select name="dd_country" id="dd_country" class="form-group">
                    <option value='0'>-- Select country --</option>

    <!-- Script -->
    <script type='text/javascript'>
        $(document).ready(function() {

            // Initialize select2
                ajax: {
                    url: "{{ route('countries') }}",
                    type: "post",
                    delay: 250,
                    dataType: 'json',
                    data: function(params) {
                        return {
                            query: params.term, // search term
                            "_token": "{{ csrf_token() }}",
                    processResults: function(response) {
                        return {
                            results: response
                    cache: true




Application Testing

Open project to terminal and type the command to start development server

$ php artisan serve


We hope this article helped you to learn about Laravel 8 load data using jquery Ajax in select2 in a very detailed way.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Find More on Laravel 8 Articles here