Select2 remote data source and load more function with laravel pagination

Published Date: 05-May-2018 | Tags: Laravel 5.5  Bootstrap 4  Ajax  Select2  

This tutorial I want to show you how to filter data within a dropdown list by using select2 remote data source and load more function with laravel 5.5.

Suppose that your server is running on port 80 and your project folder is /demo.

Note

  • I use laravelcollective to create form. So please install laravelcollective if you not yet install it. You can visit here for the installation guide.
  • I use bootstrap 4 for my UI, so please check bootstrap if you are new to bootstrap.

 

Step 1: Create Database Table

 Create table Countries with structure as below and enter some data.
country table structure
or you download sample data from here and restore to your database.

 

Step 2: Database Configuration

Edit this file /demo/.env and update your database name, username and password.

Suppose that your database name is demo, username is root, and password is empty.

laravel db config

 

Step 3: Add Route

Add these lines to this file /demo/routes/web.php.

Route::get('/select2-remote-data-source', 'Select2Controller@select2RemoteDataSource');
Route::get('/select2-load-more', 'Select2Controller@select2LoadMore');

 

Step 4: Create Model

Create model file Country.php in /demo/app.

<?php
namespace App;

use Illuminate\Database\Eloquent\Model;

class Country extends Model
{

}

 

Step 5: Create View

Create layout view file default.blade.php in /demo/resources/views/layout. (create folder layout if it does not exist)

<!DOCTYPE html>
<html lang="{{ app()->getLocale() }}">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
<!-- CSRF Token -->
    <meta name="csrf-token" content="{{ csrf_token() }}">
@yield('head')
<!-- Styles -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
    @yield('css')
</head>
<body style="padding-top: 100px;padding-bottom: 50px;background: whitesmoke">
<nav class="navbar fixed-top navbar-expand-sm navbar-dark bg-info">
    <a class="navbar-brand" target="_blank" href="http://www.codovel.com">CODOVEL.COM</a>
    @yield('nav')
</nav>
@yield('content')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>
@yield('js')
</body>
</html>

 

Create view file select2_remote_data_source.blade.php in /demo/resources/views.

@extends('layout.default')
@section('css')
    <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.4/css/select2.min.css" rel="stylesheet"/>
@endsection
@section('content')
    <div class="container">
        <div class="col-md-8 offset-md-2">
            <h1 style="font-size: 1.3rem;">Select2 load more function with laravel</h1>
            <hr/>
            <div class="form-group row required">
                {!! Form::label("country","Country",["class"=>"col-form-label col-md-2"]) !!}
                <div class="col-md-6">
                    {!! Form::select("country",[],null,["class"=>"form-control",'style'=>'width:100%']) !!}
                </div>
            </div>
        </div>
    </div>
@endsection
@section('js')
    <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.4/js/select2.min.js"></script>
    <script>
        $(document).ready(function () {
            $('#country').select2({
                ajax: {
                    url: '{{'select2-load-more'}}',
                    data: function (params) {
                        return {
                            search: params.term,
                            page: params.page || 1
                        };
                    },
                    dataType: 'json',
                    processResults: function (data) {
                        data.page = data.page || 1;
                        return {
                            results: data.items.map(function (item) {
                                return {
                                    id: item.id,
                                    text: item.name
                                };
                            }),
                            pagination: {
                                more: data.pagination
                            }
                        }
                    },
                    cache: true,
                    delay: 250
                },
                placeholder: 'Country',
//                minimumInputLength: 2,
                multiple: true
            });
        });
    </script>
@endsection

 

Step 6: Create Controller

Create controller file Select2Controller in /demo/app/Http/Cotrollers.

<?php

namespace App\Http\Controllers;


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

class Select2Controller extends Controller
{
    public function select2RemoteDataSource()
    {
        return view('select2_remote_data_source');
    }

    public function select2LoadMore(Request $request)
    {
        $search = $request->get('search');
        $data = Country::select(['id', 'name'])->where('name', 'like', '%' . $search . '%')->orderBy('name')->paginate(5);
        return response()->json(['items' => $data->toArray()['data'], 'pagination' => $data->nextPageUrl() ? true : false]);
    }
}

 

Step 7: Test

Open your browser and type http://localhost/demo/public/select2-remote-data-source. Then you will see it.

select2 remote data source and load more

Hope you can do it.


Demo


Related Posts

© 2018 All Rights Reserved.