Anonymous
07 Jul, 2017

How To Autocomplete A Search From Database In Laravel With Ajax And Javascript ?

1 Answer         8588 Views

Jiwan Thapa
07 Jul, 2017

Writing a script to autocomplete search field is quite easy in php. But, when you are working with laravel, you'll need a method defined in a controller along with a route for the same method. Assuming that, you have already got your database populated, we're going to move on from that point.

Search Form

The basic HTML element you'll need in order to build a search autocomplete functionality would be a search form. Since, we are autocomplete it without the search query string being sent to the URL, HTML <form> element won't be required here. So, lets add the search box in one of our blade file.

<input id="search" type="text" placeholder="Enter Keywords" />

Provide an id or a class to the input field so that we could call it in our jquery script. Here, we opted for an id named search.

Add jQuery.ui.js file

In order to be able to work on the search autocomplete functionality with much convenience, we can include the jquery-ui.js and jquery-ui.css files from cdn.

<link href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>

Create a method to retrieve data from database

Lets create a method in our controller that deals with displaying data in our frontend assuming the table we are working on is named posts.

<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;
class frontController extends Controller
{
    //
    public function __construct(){}

    Public function livesearch(Request $request){
        $term = $request->get('term');
        $data = DB::table('posts')->where("title","LIKE","%$term%")->get();
        foreach ($data as $result)
        {
            $results[] = ['value' => $result->title, 'link' => 'posts/'.$result->slug];
        }
        return response()->json($results);       
    }
} 	
  • The use of namespace Controller groups all the extended controllers into one in laravel and allows us to instatiate the methods from other controllers and namespaces added to it.
  • Type-hinting use Illuminate\Http\Request allows us to obtain the instance of current HTTP requests.
  • Type-hinting use DB allows us to obtain the instance of our database.
  • Public funtion __construct() will hold the data we need globally while rest of the methods we create in this controller will hold required data for their specific use.
  • Public function livesearch() will be the method that we'll use to autocomplete search form.
  • The parameters (Request $request) in our method will hold the data from HTTP request.
  • $term will hold the string sent via HTTP request.
  • $data will hold the resultsets as array that match the term sent via request.
  • Since we won't need each column value from the database result set, we'll break them down and retrieve the title and the link of each of the matching posts which is required for the autosearch functionality to be properly functional.
  • Here, we concatenated a phrase posts that we need to pass in the url for those posts to be viewable as our URL for posts is localhost/project/posts/post-slug. If your post url is plain i.e. localhost/project/post-slug, you can write it the other way as shown below skipping the array break down process.
  • Finally, we'll return the retrieved dataset as array in JSON format by using return response()->json($results); .

Alternative Method

You can use this alternative method to retrive the data from database and return in JSON format if you don't need to add any additional phrase prior to the slug in URL. Keep in mind, the autocomplete jquery script requires the value and link from each dataset in JSON format.

Public function livesearch(Request $request){
    $term = $request->get('term');
    $data = DB::table('posts')->where("title","LIKE","%$term%")->select('title as value','slug as link')->get();
    return response()->json($data);       
    }

Update web/route.php file

Since no method will be operational without a route in laravel, we need to create a route in our route.php file.

Route::get('livesearch','frontController@livesearch');

Initialize the autocomplete jquery script

Finally, we can initialize the autocomplete jquery script that we added for this purpose in our blade template file where we want the autosearch functionality to be functional. Add this script anywhere below the link for jquery-ui.js file.

<script>
$( "#search" ).autocomplete({
    source: "livesearch",
    minLength: 1,
    select:function(event,ui) { 
        location.href = ui.item.link;
    }
});
</script>
  • $( "#search" ).autocomplete() will initialize the autocomplete jquery script in the search id which is the id we added to our search form input field.
  • We can pass additional options to the autocomplete method.
  • source defines the method to obtain matching data from the database to the value entered in the field. Had it not been a laravel application, then, the source would be a filename that holds all the functions to retrieve the data from database in case of a search query. In laravel, we create methods for such actions.
  • minlength defines the minimum character count that must be entered into the input field for autocomplete() method to be initialized.
  • select:function(event,ui) or select:function(e,ui) defines the action for the event i.e. the selection of one of the item from the list where the action is defined as redirection to the item's link location.href = ui.item.link which we set in our method livesearch() from our frontController file.

More option for autocomplete jquery

You can include other options in this initialization script as well.Some of the most used options are as follows:

Option Values Description
autofocus true / false When set to true, the first item on the list will be focused by default. Default value is false.
delay integer in milliseconds It will delay the display of the results by defined time. Default value is 300.
position any combination of left right top bottom and center Defines the position of the suggestion list in relation to the input field. Default value is my: "left top", at: "left bottom", collision: "none"

In this way, you can easily set up a search field with autocomplete functionality in laravel.


102 Likes         0 Dislike         0 Comment        


Leave a comment