Laravel

Make Autocomplete search using jQuery UI in Laravel

Pinterest LinkedIn Tumblr

Step 1: Install the laravel project using the command line.

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

Step 2: Open project in code and use vs code terminal.

cd laravel7autocomplete

Step 3: find .env file in root directory setup database configuration.

DB_CONNECTION=mysql 
DB_HOST=127.0.0.1 
DB_PORT=3306 
DB_DATABASE=database_name
DB_USERNAME=database_username
DB_PASSWORD=database_password

Step 4: run Migration command

php artisan make:migration create_category_table

Now, navigate to database/migration/ directory from the project root.
Find a PHP file which ends with create_category_table and open it.

Define the table structure in the up() method.
public function up()
{
Schema::create('categories', function (Blueprint $table) {
  $table->bigIncrements('id');
  $table->string('name');
  $table->timestamps();
});
}

Step 5: Download

Download jQuery UI from its website and also download the jQuery library.

Copy download files in public/ directory

I have copied jQuery UI library in public/jqueryui/ directory.

Step 6: Model

Create Category Model.

php artisan make:model Category

Specify mass assignable Model attributes – name, and slug using the $filliable.

Completed Code

Step 7: Route

Open routes/web.php file.

Define 2 routes

Route::get('/','CategoryController@index');
Route::post('/category/getCategory/','CategoryController@getCategory')->name('category.getCategory');

The 2nd route is used for AJAX request.

Step 8: Controller

Create CategoryController Controller.

php artisan make:controller CategoryController

Open app/Http/Controllers/CategoryController.php file.
Import Category Model.

Create two methods –

index() – Load Category.index view.

getCategory() – This use to handle AJAX request. Read POST search value and assign in $search.
If $search is empty then select first 5 records from the Category table otherwise use $search in where on the name field and select first 5 records.

Loop on the fetched records. Pass $category->id in value key and $category->name in label key.

Return $response Array in JSON format.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Category;
use DB;

class CategoryController extends Controller
{
   public function index(){
      return view('Category.index');
   }

   /*
   AJAX request
   */
   public function getCategory(Request $request)
   {

    if($request->get('query'))
     {
      $query = $request->get('query');
      $data = DB::table('categories')
        ->where('name', 'LIKE', "%{$query}%")
        ->get();
      $output = '<ul class="dropdown-menu" style="display:block; position:relative">';
      foreach($data as $row)
      {
       $output .= '
       <li><a href="#">'.$row->name.'</a></li>
       ';
      }
      $output .= '</ul>';
      echo $output;
     }
   }
}

Step 9:

Create file –

Create a new directory category at resources/views/ directory.
In resources/views/category/ directory create a new index.blade.php file.
Include CSS and JS –

Specify csrf_token() in the .
Include jQuery UI CSS, jQuery and jQuery UI JS at the section.
Input fields –

Create two input fields.
1st is used to initialize jQuery UI autocomplete().
2nd is used to display selected value from the autocomplete suggestion option.
Script –

Read csrf_token from meta tag and assign in CSRF_TOKEN variable.
Initialize jQuery UI autocomplete on #category_search field.
Using source option to send AJAX post request to route(‘category.getcategory’) to fetch category list for displaying.
Also, pass CSRF_TOKEN along with search value in the data.
On successful callback pass response in response() function.
Using select option to display selected option label in the #category_search and value in #categoryid input fields.

<!DOCTYPE html>
<html>
 <head>
  <title>Laravel Autocomplete using Jquery</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>
  <style type="text/css">
   .box{
    width:600px;
    margin:0 auto;
   }
  </style>
 </head>
 <body>
  <br />
  <div class="container box">
   <h3 align="center">Laravel Autocomplete using Jquery</h3><br />
   
   <div class="form-group">
    <input type="text" name="category_name" id="category_name" class="form-control input-lg" placeholder="Enter Country Name" />
    <div id="categoryList">
    </div>
   </div>
   {{ csrf_field() }}
  </div>
 </body>
</html>

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

 $('#category_name').keyup(function(){ 
        var query = $(this).val();
        if(query != '')
        {
         var _token = $('input[name="_token"]').val();
         $.ajax({
          url:"{{ url('category/getCategory') }}",
          method:"POST",
          data:{query:query, _token:_token},
          success:function(data){
           $('#categoryList').fadeIn();  
                    $('#categoryList').html(data);
          }
         });
        }
    });

    $(document).on('click', 'li', function(){  
        $('#category_name').val($(this).text());  
        $('#categoryList').fadeOut();  
    });  

});
</script>

Step 10: Create database Seeder

Put inside of database/seeds/DatabaseSeeder.php

<?php

 use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;

use Faker\Factory as Faker;
class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
   public function run()
    {
         $faker = Faker::create();
    	foreach (range(1,10) as $index) {
	        DB::table('categories')->insert([
	            'name' => $faker->name,
	        ]);
	}
    }
}

php artisan db:seed

Step 10: Run Server

php artisan serve

Write A Comment