Showing posts with label laravel autocomplete search. Show all posts
Showing posts with label laravel autocomplete search. Show all posts

Thursday, 22 July 2021

Autocomplete Search in Laravel 8 using Typeahead.js


Autocomplete or Live Search is nice functionality, because it has give us auto suggestion or recommendations, when we have start type in input field. If you have not know but Autocomplete feature has provide helps to User in different ways like auto search suggestion when we have search some specific product or some specific category. So when we have start type then it has provide suggestion which has fetch from database and display in autocomplete search suggestion dropdown list.

Under this Laravel 8 tutorial, we will implement Autocomplete Search by using Typeahead.js library. So this is Laravel 8 Autocomplete tutorial in which you can find how to add Autocomplete Search feature in Laravel 8 Application by using Typeahead JS with Mysql database.

If you want to make Autocomplete Search feature for your web application, then typeahead.js is the best solution. Typeahead.js is a Javascript library which helps us to make an outstanding Autocomplete Search functionality in our Laravel 8 Application.

Now we have proceed for create Autocomplete Search Module in our Laravel 8 application. In this tutorial, we will create model and migration and add fake data in Mysql database and from that data we will fetch and display in autocomplete search suggestion in our Laravel 8 application. So here we will build dynamic Autocomplete Search in Laravel 8 using Typeahead JS. For this you have to follow following steps.


Autocomplete Search in Laravel 8 using Typeahead.js

How to Implement Dynamic Autocomplete Search in Laravel using Typeahead.js


  1. Step 1 : Download & Install Laravel Framework
  2. Step 2 : Make Database Connection
  3. Step 3 : Create User Table in Database
  4. Step 4 : Generate Fake Records
  5. Step 5 : Create Controller
  6. Step 6 : Create index() method in Controller
  7. Step 7 : Create Blade View File
  8. Step 8 : Create action() method in Controller
  9. Step 9 : Set Routes for Controller Method
  10. Step 10 : Start Development Server
  11. Step 11 : Check Output in Browser

Step 1 : Download & Install Laravel Framework


For build Autocomplete search feature, first we want to install latest version of Laravel framework. For this we have go to command prompt and run following command.


composer create-project --prefer-dist laravel/laravel typeahead_autocomplete


This command will create typeahead_autocomplete directory and under that directory it will download latest version of Laravel framework. After download Laravel framework, then after we have go into typeahead_autocomplete this directory. For this we have to run following command in command prompt.


cd typeahead_autocomplete


Step 2 : Make Database Connection


In second step we have make Mysql Database connection with our Laravel 8 application. For this we have to open .env file and under this we have to define MySQL credential which you can seen below.


DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=testing
DB_USERNAME=root
DB_PASSWORD=


Step 3 : Create User Table in Database


In third step, we have to create User table in Mysql database. So when we have download latest version of Laravel framework then by default User.php model class and users table migration file will be available under this Laravel framework. So for create users we have to go command prompt and run following command. This command will create users table in MySQL database.


php artisan migrate

Step 4 : Generate Fake Records


Once if you have create users table then under this steps we have to insert fake records under this table. For this we have to open database/seeders/DatabaseSeeder.php file and under this file we have to write following code.

database/seeders/DatabaseSeeder.php

<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;

use App\Models\User;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
        // \App\Models\User::factory(10)->create();

        User::factory(100)->create();
    }
}
?>


After this we have open command prompt and run following command. This command will insert 100 fake data under this users table in MySQL Database.


php artisan db:seed --force


Step 5 : Create Controller


In fifth steps, we have to create controller class under Laravel framework. For this we have to open command prompt and fun following command.


php artisan make:controller TypeaheadAutocompleteController

This command will create TypeaheadAutocompleteController.php controller class file in app/Http/Controllers folder. Under this file first we want to import User models class. For this we have to write following code at header of this class file.


use App\Models\User;


Step 6 : Create index() method in Controller


After create controller class file, now in step six, we need to create index() method under this class. So this method will load typeahead_autocomplete.blade.php file in browser.


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\User;

class TypeaheadAutocompleteController extends Controller
{
    function index()
    {
        return view('typeahead_autocomplete');
    }
}
?>





Step 7 : Create Blade View File


In this step 7, we have need to create blade view file for display html output in browser. So here we have create typeahead_autocomplete.blade.php under resources/views directory. In the blade view, we need to import Typeahead js and bootstrap 4 library for make autocomplete in Laravel 8 app.


<html>
    <head>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Typeahead JS Live Autocomplete Search in Laravel 8</title>
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
        <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.2/bootstrap3-typeahead.min.js" ></script>
    </head>
    <body>
        <div class="container">    
            <br />
            <h1 class="text-center text-primary">Typeahead JS Live Autocomplete Search in Laravel 8</h1>
            <br />
            <input type="text" name="user_name" id="user_name" class="form-control-lg" placeholder="Enter User Name..." />
        </div>
    </body>
</html>

<script>

var path = "{{ url('typeahead_autocomplete/action') }}";

$('#user_name').typeahead({

    source: function(query, process){

        return $.get(path, {query:query}, function(data){

            return process(data);

        });

    }

});

</script>


Step 8 : Create action() method in Controller


In steps 8, we have to crate action() method in Controller class file. Because this method will received ajax request from typeahead.js for fetch match data from database, and this method will send data to ajax request in JSON format.


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\User;

class TypeaheadAutocompleteController extends Controller
{
    function index()
    {
        return view('typeahead_autocomplete');
    }

    function action(Request $request)
    {
        $data = $request->all();

        $query = $data['query'];

        $filter_data = User::select('name')
                        ->where('name', 'LIKE', '%'.$query.'%')
                        ->get();

        return response()->json($filter_data);
    }
}



Step 9 : Set Routes for Controller Method


In steps 9, we need to set route for two method of controller class. For set route, we have to open routes/web.php file and under this file first we need to import TypeaheadAutocompleteController.php class file and then after write code for set route.


<?php

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\TypeaheadAutocompleteController;

Route::get('/', function () {
    return view('welcome');
});

Route::get('/typeahead_autocomplete', [TypeaheadAutocompleteController::class, 'index']);

Route::get('/typeahead_autocomplete/action', [TypeaheadAutocompleteController::class, 'action'])->name('typeahead_autocomplete.action');


Step 10 : Start Development Server


Once we have follow all above step, so here our Laravel 8 application is ready with Autocomplete Search feature. So for check output in browser, first we have need to start Laravel development server. For this we have to open command prompt and run following command. This command will start server and provide us base url of our Laravel application.


php artisan serve


Step 11 : Check Output in Browser


After start development server, now we want to check output in browser. So in browser we have hit following url for check Autocomplete Search in Laravel 8 application.


http://localhost:8000/typeahead_autocomplete


Conclusion


So under this tutorial, we have seen how easily we can implement Typeahead.js Autocomplete search in Laravel 8 framework. So making this Autocomplete Search feature, we have seen that it is very useful in our web application, because when we have type something then this feature has provide us suggestion related to text which we have type in input field, and user can get filter suggestion and from that suggestion user can select option.

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.