• We just launched and are currently in beta. Join us as we build and grow the community.

Data Table Pagination with Live Search using Laravel, jQuery, and Ajax Request

johnstallo16

Game Master
J Rep
0
0
0
Rep
0
J Vouches
0
0
0
Vouches
0
Posts
74
Likes
199
Bits
2 MONTHS
2 2 MONTHS OF SERVICE
LEVEL 1 300 XP
In this tutorial, you can learn to create a Live Search Box feature in Laravel 10 Data with Pagination. The tutorial aims to provide students and beginners with a reference for learning to create a useful feature or component of a Laravel Project. Here, I will be providing a simple web application script that demonstrates the creation of the said feature using the Laravel version 10 Framework.

What is Live Search Box?

A Live Search Box is one of the often implemented features or web features in websites or web applications. This is usually used to easily filter the specific data that matches the entered keyword on the search box input. This feature works dynamically without leaving the current page or reloading the pages which means that the new data will be automatically updated without reloading the page assets and other elements.

How to Create a Live Search Box?

There are plenty of ways to achieve the Live Search Box for the paginated data in Laravel Projects. Most of these ways are through HTTP Request. Using jQuery's Ajax Request we can achieve this kind of feature or component. We can simply initiate the Request through Ajax when there are changes made to the search box input. After the Ajax Request has been fulfilled, we can update the data with the updated ones. Check out the source code scripts I have provided below to understand it more.

Sample Scripts

The scripts below are the modified file script of my previously published Laravel Project which is the "Laravel 10: Paginate DB Table Data with Bootstrap Tutorial". Kindly click the provided link (my previously published tutorial title) if you want to learn from scratch.

The modified script result in a simple Laravel Project web page that contains a table that displays the list of members data from the database with the Pagination Feature. Using the scripts, the project will have a search box input on the front end and when the user updates the search input value, the search process will be executed and updates the table data with the members data that contains information that matches the given keyword. Here, the live search feature has the ability to preserve the searched keyword whereas the entered keyword will stay on the search input field and the searched data will remain even if the user forcibly reloads or refresh the page.

Page View File Script

The modified file is known as members.blade.php. It is a PHP file that contains the HTML and PHP codes for the elements and displays the retrieved data. This file is located in the resources/views directory of the project.

  1. <!DOCTYPE html>
  2. <html

    lang

    =

    "en"

    >
  3. <head

    >
  4. <meta

    charset

    =

    "UTF-8"

    >
  5. <meta

    http-equiv

    =

    "X-UA-Compatible"

    content

    =

    "IE=edge"

    >
  6. <meta

    name

    =

    "viewport"

    content

    =

    "width=device-width, initial-scale=1.0"

    >
  7. <title

    >

    Sample Data Pagination with Live Search using Ajax</

    title

    >
  8. <!-- Bootstrap CDN Link -->
  9. <link

    rel

    =

    "stylesheet"

    href

    =

    "https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"

    >
  10. <!-- Fontawesome CDN Link -->
  11. <link

    rel

    =

    "stylesheet"

    href

    =

    "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"

    integrity=

    "sha512-iecdLmaskl7CVkqkXNQ/ZH/XLlvWZOJyj7Yy7tcenmpD1ypASozpmT/E0iPtmFIB46ZmdtAc9eNBvH0H/ZpiBw=="

    crossorigin=

    "anonymous"

    referrerpolicy=

    "no-referrer"

    /

    >
  12. <!-- jQuery CDN JS -->
  13. <script

    src

    =

    "https://code.jquery.com/jquery-3.7.0.min.js"

    integrity=

    "sha256-2Pmvv0kuTBOenSvLm6bvfBSSHrUJ+3A7x6P5Ebd07/g="

    crossorigin=

    "anonymous"

    ></

    script

    >
  14. <!-- Bootstrap CDN JS -->
  15. <script

    src

    =

    "https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"

    ></

    script

    >
  16. <!-- Fontawesome CDN JS -->
  17. <script

    src

    =

    "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/js/all.min.js"

    integrity=

    "sha512-fD9DI5bZwQxOi7MhYWnnNPlvXdp/2Pj3XSTRrFs5FQa4mizyGLnJcN6tuvUS6LbmgN1ut+XGSABKvjN0H6Aoow=="

    crossorigin=

    "anonymous"

    referrerpolicy=

    "no-referrer"

    ></

    script

    >
  18. </

    head

    >
  19. <body

    >
  20. <div

    class

    =

    "container-md py-5"

    >
  21. <div

    class

    =

    "col-lg-5 col-md-6 col-sm-12 col-12 mx-auto my-2"

    >
  22. <!-- Search Box -->
  23. <div

    class

    =

    "input-group"

    >
  24. <span

    class

    =

    "input-group-text"

    id

    =

    "basic-addon1"

    >

    @</

    span

    >
  25. <input

    type

    =

    "search"

    class

    =

    "form-control rounded-0"

    id

    =

    "search"

    placeholder

    =

    "Search here..."

    value

    =

    "{{$kw}}"

    >
  26. </

    div

    >
  27. <!-- Search Box -->
  28. </

    div

    >
  29. <div

    class

    =

    "table-responsive"

    >
  30. <!-- Data Table -->
  31. <table

    id

    =

    "membersTbl"

    class

    =

    "table table-sm table-bordered table-striped"

    >
  32. <thead

    >
  33. <tr

    >
  34. <th

    >

    ID</

    th

    >
  35. <th

    >

    Name</

    th

    >
  36. <th

    >

    Email</

    th

    >
  37. <th

    >

    Phone</

    th

    >
  38. </

    tr

    >
  39. </

    thead

    >
  40. <tbody

    >
  41. @foreach($members as $member)
  42. <tr

    >
  43. <td

    class

    =

    "text-center"

    >

    {{$member->id}}</

    td

    >
  44. <td

    >

    {{$member->name}}</

    td

    >
  45. <td

    >

    {{$member->email}}</

    td

    >
  46. <td

    >

    {{$member->phone}}</

    td

    >
  47. </

    tr

    >
  48. @endforeach
  49. @if(count($members) <=

    0

    )
  50. <tr

    >
  51. @if(empty($kw))
  52. <!-- If No data to display -->
  53. <td

    class

    =

    "text-center"

    colspan

    =

    "4"

    >

    No Data found</

    td

    >
  54. @else
  55. <!-- If No Data match the keyword -->
  56. <td

    class

    =

    "text-center"

    colspan

    =

    "4"

    >

    No search keyword match found.</

    td

    >
  57. @endif
  58. </

    tr

    >
  59. @endif
  60. </

    tbody

    >
  61. </

    table

    >
  62. <!-- Data Table -->

  63. <!-- Pagination Link Wrapper -->
  64. <div

    id

    =

    "pagination-links"

    >
  65. {{$members->onEachSide(2)->links()}}
  66. </

    div

    >
  67. <!-- Pagination Link Wrapper -->
  68. </

    div

    >
  69. </

    div

    >
  70. </

    body

    >
  71. <script

    >
  72. // Ajax Variable
  73. var search_ajax;
  74. $(document).ready(function(){
  75. // Execute Live Searcing when search box input has character entered or change
  76. $('#search').on('input change', function(e){
  77. e.preventDefault()
  78. // current keyword value
  79. var searchTxt = $(this).val()
  80. // Get Url Parameters
  81. var urlParams = new URLSearchParams(location.search);
  82. // New Parameters aray
  83. var newParams = []
  84. urlParams.forEach((v, k) => {
  85. if(k == 'q'){
  86. // update keyword value
  87. v = searchTxt
  88. }
  89. // Add parameter to the new parameter
  90. if(searchTxt != "" && k == 'q')
  91. newParams.push(`${k}=${encodeURIComponent(v)}`);
  92. })
  93. // Update Location URL without reloading the page
  94. if(newParams.length > 0){
  95. // structuring the new URL
  96. var newLink = `{{URL::to('/')}}?`+(newParams.join('&'));
  97. // Update the location URL
  98. history.pushState({}, "", newLink)
  99. }else{
  100. if(searchTxt != ""){
  101. // Update location URL
  102. history.pushState({}, "", `{{URL::to('/')}}?q=${encodeURIComponent(searchTxt)}`)
  103. }else{
  104. // Update location URL
  105. history.pushState({}, "", `{{URL::to('/')}}`)
  106. }

  107. }

  108. if(search_ajax != undefined && search_ajax != null){
  109. // Abort Previous Search Ajax Process if exists
  110. search_ajax.abort();
  111. }
  112. // Start Search Ajax Process
  113. search_ajax = $.ajax({
  114. url:`{{URL::to('search')}}?q=${searchTxt}`,
  115. dataType:'json',
  116. error: err => {
  117. console.log(err)
  118. if(err.statusText != 'abort')
  119. alert('An error occurred');
  120. },
  121. success: function(resp){
  122. if(!!resp.members){
  123. // Data Table Body Element
  124. var tblBody = $('#membersTbl tbody')
  125. // Page Links Wrapper Element
  126. var paginationLink = $('#pagination-links')
  127. // remove current data on the table
  128. tblBody.html('')
  129. // remove current pagination links
  130. paginationLink.html('')
  131. if(!!resp.members.data){
  132. // Loop the searched data
  133. Object.values(resp.members.data).map(member => {
  134. // creating new table row
  135. var tr = $('<tr

    >

    ')
  136. // creting the new columns and data of the row
  137. tr.append(`<td

    class

    =

    "text-center"

    >

    ${member.id}</

    td

    >

    `)
  138. tr.append(`<td

    >

    ${member.name}</

    td

    >

    `)
  139. tr.append(`<td

    >

    ${member.email}</

    td

    >

    `)
  140. tr.append(`<td

    >

    ${member.phone}</

    td

    >

    `)
  141. // inserting the created data row the table
  142. tblBody.append(tr)
  143. })

  144. if(Object.keys(resp.members.data).length <=

    0

    )

    {
  145. //

    Display Message if no data

    found that is match to the keyword
  146. var tr =

    $(

    '<tr>

    ')
  147. tr.append(`<td

    class

    =

    "text-center"

    colspan

    =

    "4"

    >

    No search keyword match found.</

    td

    >

    `)
  148. tblBody.append(tr)
  149. }
  150. }
  151. // Update Pagination link
  152. if(!!resp.members.pagination_links)
  153. paginationLink.html(resp.members.pagination_links)
  154. }
  155. }
  156. })
  157. })
  158. })
  159. </

    script

    >
  160. </

    html

    >

I used CDNs link for the sources of the Bootstrap, jQuery, and Fontwesome libraries or packages which means that an internet connection is a must when browsing the web page.

Controller

The PHP file script below is the modified file content of the membersController.php. It contains the modified script of the index method of the class for rendering the web page and the new method called search. The search method of this controller class is used for retrieving the search data that is executed through Ajax Request. This file can be found in the apps/Http/Controllers directory.

  1. <?php

  2. namespace

    App\Http\Controllers;

  3. use

    App\Models\Members;
  4. use

    Illuminate\Http\Request;

  5. class

    MembersController extends

    Controller
  6. {
  7. /**
  8. * Display a listing of the resource.
  9. */
  10. public

    function

    index(

    Request $request

    )
  11. {
  12. // search keyword
  13. $kw

    =

    $request

    ->

    q

    ;

  14. if

    (

    empty

    (

    $kw

    )

    )

    {
  15. // Display All data with pagination if no keyword to search
  16. $members

    =

    Members::

    paginate

    (

    10

    )

    ;
  17. }

    else

    {
  18. // Display Filtered data with pagination if keyword exists
  19. $members

    =

    Members::

    where

    (

    'name'

    ,

    'like'

    ,

    "%{$kw}

    %"

    )
  20. ->

    orwhere

    (

    'email'

    ,

    'like'

    ,

    "%{$kw}

    %"

    )
  21. ->

    orwhere

    (

    'phone'

    ,

    'like'

    ,

    "%{$kw}

    %"

    )
  22. ->

    paginate

    (

    10

    )
  23. ->

    appends

    (

    [

    'q'

    =>

    "{$kw}

    "

    ]

    )
  24. ->

    withPath

    (

    '/'

    )
  25. ->

    withQueryString

    (

    )

    ;
  26. }
  27. // render page view
  28. return

    view(

    'members'

    ,

    [

    'members'

    =>

    $members

    ,

    'kw'

    =>

    $kw

    ]

    )

    ;
  29. }
  30. /**
  31. * Ajax Live Search Listing of the resource
  32. */
  33. public

    function

    search(

    Request $request

    )

    {
  34. // search keyword
  35. $kw

    =

    $request

    ->

    q

    ;
  36. if

    (

    empty

    (

    $kw

    )

    )

    {
  37. // Display All data with pagination if no keyword to search
  38. $members

    =

    Members::

    paginate

    (

    10

    )

    ;
  39. }

    else

    {
  40. // Display Filtered data with pagination if keyword exists
  41. $members

    =

    Members::

    where

    (

    'name'

    ,

    'like'

    ,

    "%{$kw}

    %"

    )
  42. ->

    orwhere

    (

    'email'

    ,

    'like'

    ,

    "%{$kw}

    %"

    )
  43. ->

    orwhere

    (

    'phone'

    ,

    'like'

    ,

    "%{$kw}

    %"

    )
  44. ->

    paginate

    (

    10

    )
  45. ->

    appends

    (

    [

    'q'

    =>

    "{$kw}

    "

    ]

    )
  46. ->

    withPath

    (

    '/'

    )
  47. ->

    withQueryString

    (

    )

    ;
  48. }

  49. // converting array to laravel collection
  50. $membersCollection

    =

    collect(

    $members

    )

    ;
  51. // merging queried data with pagination links HTML
  52. $membersCollection

    =

    $membersCollection

    ->

    merge

    (

    [

    'pagination_links'

    =>

    (

    string)

    $members

    ->

    onEachSide

    (

    2

    )

    ->

    links

    (

    )

    ]

    )

    ;

  53. // returning the response data as JSON string
  54. return

    collect(

    [

    "members"

    =>

    $membersCollection

    ->

    all

    (

    )

    ]

    )

    ->

    toJson

    (

    )

    ;
  55. }
  56. /**
  57. * Show the form for creating a new resource.
  58. */
  59. public

    function

    create(

    )
  60. {
  61. //
  62. }

  63. /**
  64. * Store a newly created resource in storage.
  65. */
  66. public

    function

    store(

    Request $request

    )
  67. {
  68. //
  69. }

  70. /**
  71. * Display the specified resource.
  72. */
  73. public

    function

    show(

    Members $members

    )
  74. {
  75. //
  76. }

  77. /**
  78. * Show the form for editing the specified resource.
  79. */
  80. public

    function

    edit(

    Members $members

    )
  81. {
  82. //
  83. }

  84. /**
  85. * Update the specified resource in storage.
  86. */
  87. public

    function

    update(

    Request $request

    ,

    Members $members

    )
  88. {
  89. //
  90. }

  91. /**
  92. * Remove the specified resource from storage.
  93. */
  94. public

    function

    destroy(

    Members $members

    )
  95. {
  96. //
  97. }
  98. }


Routes

Finally, here's the last modified PHP file known as web.php. The file contains the routing script of the project for viewing the page content and retrieving data using Ajax Request. The file is located in the routes directory.

  1. <?php

  2. use

    Illuminate\Support\Facades\Route;
  3. use

    App\Http\Controllers\MembersController;

  4. /*
  5. |--------------------------------------------------------------------------
  6. | Web Routes
  7. |--------------------------------------------------------------------------
  8. |
  9. | Here is where you can register web routes for your application. These
  10. | routes are loaded by the RouteServiceProvider and all of them will
  11. | be assigned to the "web" middleware group. Make something great!
  12. |
  13. */

  14. // Route::get('/', function () {
  15. // return view('welcome');
  16. // });
  17. Route::

    controller

    (

    MembersController::

    class

    )

    ->

    group

    (

    function

    (

    )

    {
  18. Route::

    get

    (

    '/'

    ,

    'index'

    )

    ;
  19. Route::

    get

    (

    '/search'

    ,

    'search'

    )

    ;
  20. }

    )

    ;

Snapshots

Here are some snapshots of the modified Laravel Project.

Page Interface

Sample Search Result #1

Sample Search Result #2

There you go! I also have provided the complete modified source code zip file of the sample Laravel Project on this website and it is free to download. The download button can be found below this tutorial's content. Feel free to download and modify the source code the way you wanted to enhance your programming capabilities using PHP and Laravel 10 Framework.

How to Run the source code?

  • Please start the Apache and MySQL servers of your XAMPP or equivalent software.
  • Extract the source code folder into the XAMPP's htdocs directory or equivalent directory.
  • Create a new database named dummy_db
  • Open the terminal or command prompt and redirect the directory to the source code folder
  • Run the php artisan migrate command
  • Run the php artisan make:seeder MembersSeeder command
  • Run the php artisan serve command
  • Browse the application.

That's it! I hope this Data Table Pagination with Live Search using Laravel, jQuery, and Ajax Request Tutorial will help you with what you are looking for and you'll find something useful for your current and future PHP or Laravel Projects.

Explore more on this website for more Tutorials and Free Source Codes.

Happy Coding =)


Download
You must upgrade your account or reply in the thread to view the hidden content.
 

452,292

324,135

324,143

Top