Friday 20 April 2018

Live search in Laravel using AJAX



In this tutorial, We will learn the process of making a live search in Laravel and AJAX. If we have on a blog or any ecommerce website, a search texbox is always an required feature of Website User Interface. Now a days using of simple search bar is left. Because a live search of data is enough more useful than a plain search bar because it will load data of content in real time without refresh of web page. This will increment the chance of increase a sale because the customer can see the more section of related products.

For demonstrate the functionality of live search, We will make customer table and search box for search live data through all column of customer table and display filter data on web page.



Create the Controller


First we have to make database connection in Laravel application and then after making of database connection we have to create controller in Laravel. For this we have to write following command in your terminal.


php artisan make:controller LiveSearch


Now go tp app/Http/controller/LiveSearch.phpand paste the following code in it.


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;

class LiveSearch extends Controller
{
    function index()
    {
     return view('live_search');
    }

    function action(Request $request)
    {
     if($request->ajax())
     {
      $output = '';
      $query = $request->get('query');
      if($query != '')
      {
       $data = DB::table('tbl_customer')
         ->where('CustomerName', 'like', '%'.$query.'%')
         ->orWhere('Address', 'like', '%'.$query.'%')
         ->orWhere('City', 'like', '%'.$query.'%')
         ->orWhere('PostalCode', 'like', '%'.$query.'%')
         ->orWhere('Country', 'like', '%'.$query.'%')
         ->orderBy('CustomerID', 'desc')
         ->get();
         
      }
      else
      {
       $data = DB::table('tbl_customer')
         ->orderBy('CustomerID', 'desc')
         ->get();
      }
      $total_row = $data->count();
      if($total_row > 0)
      {
       foreach($data as $row)
       {
        $output .= '
        <tr>
         <td>'.$row->CustomerName.'</td>
         <td>'.$row->Address.'</td>
         <td>'.$row->City.'</td>
         <td>'.$row->PostalCode.'</td>
         <td>'.$row->Country.'</td>
        </tr>
        ';
       }
      }
      else
      {
       $output = '
       <tr>
        <td align="center" colspan="5">No Data Found</td>
       </tr>
       ';
      }
      $data = array(
       'table_data'  => $output,
       'total_data'  => $total_row
      );

      echo json_encode($data);
     }
    }
}







Now We have seen code and understand how code is working here. First we have create as index function which load view file we will create in the next step. After this we have we create one more function action that will received variable from search textbox through Ajax request and execute database query for search or filter data. This query will fetch all data from customer database where particular search query will match any table column of customer table data and finally it will converted that filter data into HTML format and return as response.

Create a View

Now here our controller is ready, So We will move to next step for create a view for search bar. For this we have to go to resources/views/live_search.blade.php. NExt we have add the following code into.


<!DOCTYPE html>
<html>
 <head>
  <title>Live search in laravel using AJAX</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
 </head>
 <body>
  <br />
  <div class="container box">
   <h3 align="center">Live search in laravel using AJAX</h3><br />
   <div class="panel panel-default">
    <div class="panel-heading">Search Customer Data</div>
    <div class="panel-body">
     <div class="form-group">
      <input type="text" name="search" id="search" class="form-control" placeholder="Search Customer Data" />
     </div>
     <div class="table-responsive">
      <h3 align="center">Total Data : <span id="total_records"></span></h3>
      <table class="table table-striped table-bordered">
       <thead>
        <tr>
         <th>Customer Name</th>
         <th>Address</th>
         <th>City</th>
         <th>Postal Code</th>
         <th>Country</th>
        </tr>
       </thead>
       <tbody>

       </tbody>
      </table>
     </div>
    </div>    
   </div>
  </div>
 </body>
</html>

<script>
$(document).ready(function(){

 fetch_customer_data();

 function fetch_customer_data(query = '')
 {
  $.ajax({
   url:"{{ route('live_search.action') }}",
   method:'GET',
   data:{query:query},
   dataType:'json',
   success:function(data)
   {
    $('tbody').html(data.table_data);
    $('#total_records').text(data.total_data);
   }
  })
 }

 $(document).on('keyup', '#search', function(){
  var query = $(this).val();
  fetch_customer_data(query);
 });
});
</script>


Now we have discuss above code. In body tag we have use Bootstrap panel for display customer data in table format with on search textbox. And in below we can see Jquery code in which we have use Ajax script.

Here Ajax script will pick the value from search textbox as we have type into for search something. It will send value to action method of LiveSearch controller. Under this method it will search data into database according to value of search textbox and get the response back to Ajax request. Once it has received then it will display response of data on web page in HTML table format.

Set the Routes


Lastly we want to set the route for LiveSearch controller two method which we have seen, for this we have to go to routes/web.php and write following code into it.


<?php

Route::get('/live_search', 'LiveSearch@index');
Route::get('/live_search/action', 'LiveSearch@action')->name('live_search.action');

?>


So, here we have discuss how to make live search in Laravel by using Ajax by using simple coding method.

32 comments:

  1. Very useful example, what about pagination?

    ReplyDelete
  2. Thank you this tutorial help me very much

    ReplyDelete
  3. hello sir
    it is not working.

    ReplyDelete
  4. Hello friends

    in the beginning i want to thank you for this great work, i am following you to learn laravel but i found issue in this part the search does not work with Arabic language if i search by numbers or by english language it is work correctly but with Arabic does not work, can you help me to solve this issue please?

    ReplyDelete
    Replies
    1. it's working with arabic language also by adding on the head HTML tag

      meta charset="UTF-8"

      Delete
  5. dears
    this toturial working only with english language and does not work with arabic also working with numbers at least two digit with one digit does not work can you help me to solve this issue with arabic language
    many thanks for you i learned many things from your lessons

    ReplyDelete
    Replies
    1. it's work with arabic also by add
      meta charset="UTF-8"
      in the head tag

      Delete
  6. How can we append pagination in this case ?

    ReplyDelete
  7. hey please i wish a live search in symfony too i tried to implement this script on symfony but now way

    ReplyDelete
  8. new to laravel. can i get the database?

    ReplyDelete
  9. the ajax doesnot working

    ReplyDelete
    Replies
    1. paste the code
      $(document).on('keyup', '#search', function(){
      var query = $(this).val();
      fetch_customer_data(query);
      });
      });

      at top rather than bottom, there is a bug with the control flow

      Delete
  10. thanks it works

    ReplyDelete
  11. thank again !! Hope make new video tutorial

    ReplyDelete
  12. Great Job, excellent skills. Keep helping...

    ReplyDelete
  13. Thanks brother make your helping mind bigger

    ReplyDelete
  14. how to add edit and show function in index page table i did using this a href="{{URL::to(student/'.$row->id.'/edit)}}"> EDIT but it does not work

    ReplyDelete
  15. Laravel and AJX are a great match for live search. I have seen that people mostly use Laravel Ajax combo for creating live search, like this one: https://www.cloudways.com/blog/live-search-laravel-ajax/ However, there is now vue that can be used too. What is your take on vue?

    ReplyDelete
  16. This comment has been removed by the author.

    ReplyDelete
  17. I have another table in the same blade and data rows are spreading to another table as well. How to prevent data raw inserting in to rest of the tables? Thank you.

    ReplyDelete
  18. thanks dear
    show me this error
    jquery.min.js:2 GET http://127.0.0.1:8000/live_search/action?query= 500 (Internal Server Error)

    ReplyDelete
  19. dont work this code. return 500 (Internal Server Error) error.

    ReplyDelete
  20. if i want to show pagination link, how i can do it?

    ReplyDelete