Laravel 8 Load Data using jQuery AJAX in Select2

Share this Article
Reading Time: 7 minutes
476 Views

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: http://127.0.0.1:8000

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.

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

Create Model and Migrations

Open project into terminal and run these commands.

$ 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.

<?php

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->id();
            $table->char("iso", 2);
            $table->string("name", 50);
            $table->string("nicename", 50);
            $table->char("iso3", 3)->nullable();
            $table->smallInteger("numcode")->nullable();
            $table->integer("phonecode")->nullable();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('countries');
    }
}

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

<?php

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.

<?php

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']}%")
                ->get();
        } else {

            $data = Country::select(["id", "nicename"])
                ->get();
        }

        $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="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>

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>
<html>

<head>

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

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">

    <!-- jQuery -->
    <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>
</head>

<body>

    <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">
                <p>
                    <label>Select Country</label>
                </p>
                <select name="dd_country" id="dd_country" class="form-group">
                    <option value='0'>-- Select country --</option>
                </select>
            </div>
        </div>
    </div>

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

            // Initialize select2
            $("#dd_country").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
                }
            });

        });
    </script>

</body>

</html>

Application Testing

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

$ php artisan serve

URL – http://127.0.0.1:8000/data

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

Leave a Comment