2013-12-21

This tutorial is one more addition to my “Building a shop with Laravel” tutorial series.

In this tutorial I will share what I have learned while building a “Smart Search” feature into a big project. What is smart search? Take a look at the GIF below to see what I mean:



The real, working demo of this type of search is also available at:
http://laravel-smart-search.gopagoda.com/

And the source for the demo is at https://github.com/msurguy/laravel-smart-search

Smart Search is a type of autocomplete search that can search through multiple types of content that your website is serving. Let’s say you have an online shop that has products and categories. The most basic example of use of smart search is to let the user search through categories and products without specifying what type of content they are looking for. The application should be able to give the user a few possible results and placing them in proper types of content that the application has.

This type of search could be incredibly useful in certain cases and increase discoverability of your content by the users. Instead of going to a separate page that shows the results the users could just start typing a part of the word they are looking for and see results immediately.

How would you go about implementing that kind of search in a Laravel application?

Choosing an autocomplete library

I don’t like reinventing the wheel so I use off the shelf tools to build my projects quickly. In order to implement a smart search you need an autocomplete plugin. There are lots of existing autocomplete libraries available out there :

Typeahead.js plugin by Twitter - http://twitter.github.io/typeahead.js/

Built in typeahead plugin in Bootstrap version 2.

Selectize.js by Brian Reavis - https://github.com/brianreavis/selectize.js

about 1000 more.

While there are so many options, I chose Selectize.js for all of my cool search/tagging/autocomplete projects. Selectize transforms any “select” element into a text input that allows tagging, selecting multiple items, smart searching, remote data loading and more. I am using it on many websites already (mainly for tagging/autocomplete):

http://bootsnipp.com/

http://builtwithlaravel.com

http://www.laravel-tricks.com

I could write a book on using Selectize.js for many different solutions improving user interface, but for the purpose of this tutorial I will only show you how to use its ability to separate autocomplete results by different types of content using “optgroup” tags.

Getting and installing Selectize.js

So the first thing to proceed with this tutorial is to download Selectize.js, specifically you need the whole “dist” directory that you can then place somewhere in the “public” folder of your Laravel application. I placed the downloaded “dist” folder into “public/vendor/selectize” folder.

Now if I want to use the plugin in my application, I can place the following HTML and JS in my view file:

Great! We now can use the magical powers of Selectize to beautifully present our search results using this great jQuery plugin. What’s left for us is to create a data source that Selectize would use to populate search result options that that user would choose from.

Planning the search results API

Let’s take a look at how the process of  the search looks like, from start to finish, client side and server side:



The Selectize plugin needs to retrieve data that has the same format for all items received from the API in order for us to be able to display it properly in the dropdown. Let’s come up with the common data format so that we can then use it in Selectize to show the results in categories and in products. Here is an example JSON data that we wold like to receive from the application’s API upon searching:

As you  can see, the  value of “class” will be what separates the content by type (“category” or “product”). A bit later we will build out the API that will give us result like the JSON above. For now, let’s make Selectize work with this kind of data. I have played with Selectize.js enough to come up with a script that will parse the above JSON and provide a nice dropdown for the user to use:



Parsing the JSON to display results with Selectize

Selectize can easily work with “optgroup” type of “select” HTML element, and by using the available options you can load the data dynamically from the server and group it by a specific value (in our case “class”).

I won’t get too much into all Selectize’s available options, but the way to make it work with a Laravel application is as follows.

Place these 3 lines in the Blade template to pass the URL of the root of your application to javascript:

Place this script where you want to initialize the Selectize plugin, (I have it in “public/js/main.js” which I then load into the layout.blade.php):

You can use this snippet of code to load the data from the API and display it nicely in the drop down. Whew, the last part is left – building the actual API that will provide us with consistently formatted JSON data feeding the Selectize options.

Building the API

Thankfully, Laravel makes it super easy to build APIs and Eloquent makes it a breeze searching for data that matches some parameter. Let’s get our hands dirty in some beautiful PHP code (sounds contradicting, doesn’t it?). First, let’s create an empty SearchController class, place it in “app/controllers/Api/SearchController.php“:

Now, let’s create a route that will use an action (for example “index”) of that controller when it receives a “GET” request to the “api/search” route, in routes.php file :

The foundation has been laid, now we only need to populate the “index” action of the controller. Let’s think about that for a minute. The index action should do the following things:

Receive a string of text (search query) that the data needs to be matched against.

Go through products and categories, matching their names (or any other data) against the search query and converting the result of matched entries to an array using Eloquent’s “toArray()” method.

Append extra parameters to each array element of the results – such as icon and type of the result item.

Merge all arrays together to have one list of data that has the same format.

Return the single array of data as JSON so that Selectize can process it and show it to the user.

Let’s create a skeleton of the index action that we can then fill up to implement the functionality listed above:

To select the products that match the search query, we will use the following Eloquent query:

In the similar way, we will select the categories that match the search query:

The last part (and the one that I had to come up with) is to create a shorthand function that we could use to append an arbitrary value to each element of the returned array, such as an icon, because categories don’t have icons, whereas the products do. This function is then modified a bit to append a URL that will be linking to the item of the search result (in my example, the url is based on the “slug” of each element), the two functions are below:

These functions are used in the index action as follows:

The whole code for the index action of the SearchController that provides the JSON data to the Selectize plugin:

That’s it! The smart search should now work displaying the product and category names and taking the user to the selected result. If you wanted to add any more data types to the result, you could easily do it using Eloquent and my normalization functions.

This wraps up the tutorial, I hope you enjoyed it. Let me know if you have any questions/suggestions about this implementation, I’d be happy to hear your thoughts.

Get complete source for this tutorial at this Github Repository : https://github.com/msurguy/laravel-smart-search

Enjoying my writing? Support me by buying my book from Manning publications, Laravel in Action : 

Show more