Laravel Ajax autocomplete search

Laravel Ajax autocomplete search

In this tutorial, I will give you an example of the “How to use Autocomplete Search using Ajax in Laravel“, So you can easily apply it with your laravel 5, laravel 6, laravel 7, and laravel 8 application.

First, what we’re doing here, This is the example :

ajax auto complete search in laravel

ajax auto complete search in laravel

Need and Importance of Autocomplete Search in Laravel

The autocomplete search is also a part of every application, mostly when we working on e-commerce or business listing directory projects in Laravel applications, This search is similar to a normal search but the suggestion data in the select box make this much easier to find related results for users.

Fetch Records without any package or plugin script in the Search Bar

There are different types of plugins, packages, and scripts that are available for autocompleting search, these scripts, and packages make our application heavier, So we simply use ajax to fetch related results according to user input keywords, and when you select data on the select box in the dropdown search bar it will redirect you to your selected result.

Using this method in the given example you can fetch data from the collection of single or multiple models and show these results on the select box dropdown in the Laravel application.

We have a table test_table_1 in our database and we stored some dummy data using Faker in this table.

autocomplete search in laravel

App\Model\TestTable1

<?php

namespace App\Model;

use Illuminate\Database\Eloquent\Model;

class TestTable1 extends Model
{
    protected $table = 'test_table_1';
}

routes\web.php

#Ajax AutoComplete Search
Route::get('/search-form','TestController@searchform')->name('search.form');
Route::get('autosearch',array('as'=>'searchajax','uses'=>'TestController@autoCompleteSearch'));
Route::any('auto-search-result','TestController@autoCompleteSearchResult')->name('search.list');

App\Http\Controllers\TestController

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Session;
use App\Model\TestTable1;


class TestController extends Controller
{

   public function searchform(){
   return view('search');
   }

   //Search Data from Database and put it into the select box in Results
   public function autoCompleteSearch(Request $request) {

    $query = $request->get('search','');

    $tabledata = TestTable1::select('id','name','email','address')->where('name','LIKE','%'.$query.'%')->get();
      $getdata = $tabledata;
        $data=array();
        foreach($getdata as $tabledata){
            $data[]=array('value'=>$tabledata->name,'id'=>$tabledata->id);
            }
            if(count($data) && !empty( $query )){
                $dataVal = '<ul class="no-bullets" id="selectval">';
                foreach($data as $key=>$value){
                  $dataVal .=  '<li onClick="selectval('."'".$value['value']."'".')">'.$value['value'].'</li>';
                }
                $dataVal .='</ul>';
                }else{
                  $dataVal = '<ul id="selectval">';
                  $dataVal .=  '<li>No result found..!</li>';
                  $dataVal .='</ul>';
                }
                  echo $dataVal;
                  exit();
    }

    //Find Result Accroding to Request Parameter
    public function autoCompleteSearchResult(Request $request)
    {
       if($request->has('search_keyword')){
       $search=$request->get('search_keyword');
       $data=TestTable1::where('name','like','%'.$search.'%')->first();
       return view('view',['data' => $data]);
      }
    }

}

resources\views\search.blade.php

laravel ajax autocomplete search
<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Ajax autocomplete search in Laravel-8bityard</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
    <script src="https://kit.fontawesome.com/a076d05399.js"></script>

<style>
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@200;300;400;500;600;700&display=swap');
*{
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Poppins', sans-serif;
}

body{
  background: #644bff;
  padding: 0 20px;
}

::selection{
  color: #fff;
  background: #664AFF;
}

.wrapper{
  max-width: 450px;
  margin: 150px auto;
}

.wrapper .search-input{
  background: #fff;
  width: 100%;
  border-radius: 5px;
  position: relative;
  box-shadow: 0px 1px 5px 3px rgba(0,0,0,0.12);
}

.search-input input{
  height: 55px;
  width: 100%;
  outline: none;
  border: none;
  border-radius: 5px;
  padding: 0 60px 0 20px;
  font-size: 18px;
  box-shadow: 0px 1px 5px rgba(0,0,0,0.1);
}

.no-bullets {
    list-style-type: none;
}

.search-input.active input{
  border-radius: 5px 5px 0 0;
}

.search-input .autocom-box{
  padding: 0;
  opacity: 0;
  pointer-events: none;
  max-height: 280px;
  overflow-y: auto;
}

.search-input.active .autocom-box{
  padding: 10px 8px;
  opacity: 1;
  pointer-events: auto;
}

.autocom-box li{
  list-style: none;
  padding: 8px 12px;
  display: none;
  width: 100%;
  cursor: default;
  border-radius: 3px;
}

.search-input.active .autocom-box li{
  display: block;
}
.autocom-box li:hover{
  background: #efefef;
}

.search-input .icon{
  position: absolute;
  right: 0px;
  top: 0px;
  height: 55px;
  width: 55px;
  text-align: center;
  line-height: 55px;
  font-size: 20px;
  color: #644bff;
  cursor: pointer;

}
.TextOverride
{
 color: white !important;
}
</style>
</head>
  <body>
    <div class="wrapper">
      <h3 class="TextOverride" align="center">Autocomplete Search with Result using Ajax in Laravel www.8bityard.com</h3>
      <br>
      <form name="auto_search" id="suggestion" method="post" action="{{route('search.list')}}">
      @csrf
      <div class="search-input">
        <a href="" target="_blank" hidden></a>
        <input type="text" class="form-control" placeholder="Type to search..." id="search_text" name="search_keyword">
        <div id="suggesstion-box"></div>
        <div class="icon"><i class="fas fa-search"></i></div>
      </div>
    </form>
    </div>
 </body>
</html>

  <script>
    $(document).ready(function(){
    $("#search_text").keyup(function(){
    $.ajax({
    type: "GET",
    url: "{{ route('searchajax') }}",
    data:'search='+$(this).val(),
    success: function(data){
      $("#suggesstion-box").show();
      $("#suggesstion-box").html(data);
    }
    });
        if($("#search_text").val() == ''){
          $("#suggesstion-box").hide();
        }
    });
    });
    function selectval(val) {
    $("#search_text").val(val);
    $('#suggestion')[0].submit();
    $("#suggesstion-box").hide();
 }
</script>

resources\views\view.blade.php

ajax auto complete search in laravel
<!DOCTYPE html>
<html lang="en">
   <head>
      <title>Autocomplete Search with Result using Ajax in Laravel www.8bityard.com</title>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
   </head>
   <body>
      <div class="container">
      <h3 class="TextOverride" align="center">Autocomplete Search with Result using Ajax in Laravel www.8bityard.com</h3>
         <div class="card">
            <form>
               <div class="card-header">View Result</div>
               <div class="card-body">
                  <div class="row">
                     <div class="col-md-6">
                        <label for="name">Name :</label>
                        <input type="text" class="form-control" value="{{$data->name}}" readonly>
                     </div>
                     <div class="col-md-6">
                        <label for="email">Email :</label>
                        <input type="text" class="form-control" value="{{$data->email}}" readonly>
                     </div>
                     <div class="col-md-6">
                        <label for="address">Address :</label>
                        <input type="text" id="title" class="form-control" value="{{$data->address}}" readonly>
                     </div>
               </div>
               </div>
         </div>
         </form>
      </div>
   </body>
</html>

Run The Application :

 http://127.0.0.1:8000/search-form

Now, you can see the output in the given below images, we have successfully implemented the autocomplete search using Ajax in the Laravel application.

dynamic autocomplete search in laravel

ajax autocomplete search laravel

result using ajax

display result ajax

view result data

In this article, we learned “ Ajax Autocomplete Search in Laravel without using any package and autocomplete jquery Cdn ”, I hope this article will help you with your Laravel application Project.

Read also : Sidebar Active Class with Menu Open in Laravel.