Creating an Ajax search function in laravel

If we want to search for information in our application, it might be useful to perform the search
asynchronously. That way, the user won’t have to be taken to a new page and have all the assets
refreshed. Using Laravel and JavaScript, we can perform this search in a very simple manner.
Getting ready
For this recipe, we’ll need a working installation of Laravel.
How to do it…
To complete this recipe, follow these steps:
1. In the controllers directory, create a file named SearchController.php:
class SearchController extends BaseController {
public function getIndex()
return View::make(‘search.index’);
public function postSearch()
$return = array();

$term = Input::get(‘term’);
$books = array(
array(‘name’ => ‘Alice in Wonderland’, ‘author’ => ‘Lewis
array(‘name’ => ‘Tom Sawyer’, ‘author’ => ‘Mark
array(‘name’ => ‘Gulliver\’s Travels’, ‘author’ =>
‘Jonathan Swift’),
array(‘name’ => ‘The Art of War’, ‘author’ => ‘Sunzi’),
array(‘name’ => ‘Dracula’, ‘author’ => ‘Bram Stoker’),
array(‘name’ => ‘War and Peace’, ‘author’ =>
foreach ($books as $book) {
if (stripos($book[‘name’], $term) !== FALSE) $return[] =
return Response::json($return);
2. In the routes.php file, register the controller:
Route::controller(‘search’, ‘SearchController’);
3. In the views directory, create a folder named search, and in that folder, create a file
named index.php:

<!DOCTYPE html>
<meta charset=utf-8 />
<title>AJAX Search</title>
<script type=”text/javascript”
<form id=”search-form”>
<input name=”search” id=”term”> <input type=”submit”>
<div id=”results”></div>
$(function() {
$(“#search-form”).on(“submit”, function(e) {

var search_term = $(“#term”).val();
var display_results = $(“#results”);
var results = ”;
$.post(“search/search”, {term: search_term}, function(data)
if (data.length == 0) {
results = ‘No Results’;
} else {
$.each(data, function() {
results += + ‘ by ‘ + + ‘<br>’;

How it works…

We first create a RESTful controller that holds two methods: one for our main page and one
to process the search. On our main page, we have a single text field and a submit button.
When the form is submitted, our JavaScript will post the form to our search page. If there are
results, it will loop through them and display them in our results div.
For our postSearch() method, we use an array as our data source. When a search is
posted, we then loop through the array to see if the string matches any of our titles. If so,
the value is added to an array and that array is returned as a JSON.

Leave a Reply

Your email address will not be published. Required fields are marked *