This website uses cookies

Our website, platform and/or any sub domains use cookies to understand how you use our services, and to improve both your experience and our marketing relevance.

Create Laravel Search Box With Live Results Using AJAX jQuery

Updated on December 13, 2021

6 Min Read
laravel search bar

The Laravel search bar lets your users quickly find answers to their search queries. If you run a well-developed blog or ecommerce site with hundreds of pages categorized, your clients might find it exceptionally troublesome to discover what they’re seeking out.

Think of Laravel search as a way for clients to avoid getting stuck in a navigational maze. In case they can’t discover a sensible route to follow, they’ll turn back to the conventional methods that are guided.

You might also like: Build Live Search Box Using PHP, MySQL And AJAX

Experience Seamless Laravel Hosting with Cloudways!

Elevate Your Laravel Experience with Cloudways’ Managed Hosting – Where Expertise Meets Exceptional Performance.

Prerequisites

Before proceeding forward, I assume you have a Laravel application installed on a server. For the purpose of this article, I am using:

  • Linux/Unix or WAMP/XAMPP environment
  • Laravel 5.5
  • PHP 7.1
  • MySQL
  • Web server (Apache, NGINX or integrated PHP web server for testing)

To fulfill all the requirements, I have installed Laravel on Cloudways Laravel server because it has everything I’ll need for this project. If you do not have an account on Cloudways, signup for free.

The Laravel search form offers multiple benefits over conventional methods of searching:

  • Possible results start to appear as a user inputs their search term
  • The Laravel search bar starts to filter the results as the user continues to type in
  • Users can remove extra characters to see a broader range of results
  • Users don’t need to refresh the web page after every search
  • The search time is decreased

Open the Applications tab in the Cloudways platform. In the Application Access Detail, you will see the database credentials for your application. Now go to the .env file, located in the application public root folder and add the credentials there.

DB_CONNECTION=mysql

DB_HOST=127.0.0.1

DB_PORT=3306

DB_DATABASE= your.database.name                                                                                                                            

DB_USERNAME= your.database.username                                                                                                                             

DB_PASSWORD= your.database.password

mysql-access

Read More About: Connecting Laravel with Firebase Real Time Database

Create the Migration

Go to the Cloudways platform, and launch the SSH terminal. Once it is up, go to the root of your application with the following commands.

cd applications
cd <yourapplicationname>/public_html

Now that you are in the application folder, type the following command to create the migration for the product.

php artisan make:migration create_products_table

Now that you have created the migration, go to database/migration/<date>_create_products_table.php file and paste the following code in it.

<?php



use Illuminate\Support\Facades\Schema;

use Illuminate\Database\Schema\Blueprint;

use Illuminate\Database\Migrations\Migration;



class CreateProductsTable extends Migration

{

   /**

    * Run the migrations.

    *

    * @return void

    */

   public function up()

   {

       Schema::create('products', function (Blueprint $table) {

           $table->increments('id');

           $table->timestamps();

           $table->string('Title');

           $table->string('Description');

           $table->integer('price');

       });

   }



   /**

    * Reverse the migrations.

    *

    * @return void

    */

   public function down()

   {

       Schema::dropIfExists('products');

   }

}

Stop Wasting Time on Servers

Cloudways handle server management for you so you can focus on creating great apps and keeping your clients happy.

Now that the migration is up, run the following command in the terminal:

php artisan migrate

The next step is the migration of the table schema into the database, Go to the database by clicking the Launch Database Manager, and populate the table with dummy data. For a seamless migration experience, consider the advantages of Laravel hosting tailored to your needs.

Create the Controller

Now that the database table is ready, the next step is the creation of the controller. Type the following command in your terminal.

php artisan make:controller SearchController

Now go to app/Http/controller/SearchController.php and paste the following code in it

<?php



namespace App\Http\Controllers;



use Illuminate\Http\Request;

use DB;




class SearchController extends Controller

{

   public function index()

{

return view('search.search');

}



public function search(Request $request)

{

if($request->ajax())

{

$output="";

$products=DB::table('products')->where('title','LIKE','%'.$request->search."%")->get();

if($products)

{

foreach ($products as $key => $product) {

$output.='<tr>'.

'<td>'.$product->id.'</td>'.

'<td>'.$product->title.'</td>'.

'<td>'.$product->description.'</td>'.

'<td>'.$product->price.'</td>'.

'</tr>';

}



return Response($output);



   }



   }



}

}




Read More About: Working With Controllers in Laravel

Now let’s take a close look at this code and understand what’s happening here.  First, I created an index function which returns the view (I will create the view in the next step). After that, there is another function search that takes the variable from the Laravel search bar, and pass it to the AJAX call, executing a database query. This will fetch all the data from product database where title matches the query. Finally, I created the output in HTML format and return it as a response.

Create the View

Now that the Controller is ready, I will next create the view for the search bar. Go to resources/views/search and create a file named as search.blade.php. Next, add the following code in it.

<!DOCTYPE html>

<html>

<head>

<meta name="_token" content="{{ csrf_token() }}">



<title>Live Search</title>

<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>

</head>

<body>

<div class="container">

<div class="row">

<div class="panel panel-default">

<div class="panel-heading">

<h3>Products info </h3>

</div>

<div class="panel-body">

<div class="form-group">

<input type="text" class="form-controller" id="search" name="search"></input>

</div>

<table class="table table-bordered table-hover">

<thead>

<tr>

<th>ID</th>

<th>Product Name</th>

<th>Description</th>

<th>Price</th>

</tr>

</thead>

<tbody>

</tbody>

</table>

</div>

</div>

</div>

</div>

<script type="text/javascript">

$('#search').on('keyup',function(){

$value=$(this).val();

$.ajax({

type : 'get',

url : '{{URL::to('search')}}',

data:{'search':$value},

success:function(data){

$('tbody').html(data);

}

});



})

</script>

<script type="text/javascript">

$.ajaxSetup({ headers: { 'csrftoken' : '{{ csrf_token() }}' } });

</script>

</body>

</html>

Read More About: Working With Views in Laravel

Now let’s take a deeper look in the code and understand what’s happening here.

In the head tag, I created a meta tag, which will allow the AJAX call to be executed on the server. Next, I have included Bootstrap, CSS and a jQuery library.

In the body tag I have create a simple UI for displaying the product information using Bootstrap CSS. And, then I have used an Ajax Script. Now this is the important part to understand.

The AJAX script pick the value from the Laravel search bar as soon as you type in. It sends the value to the /search url of your application which will execute the second function of the controller. It will make the search in the DB and get the response back in this AJAX code. Once it is received, the response will be displayed in the HTML format.

The second AJAX script is used to validate the token to ensure AJAX script executable.

Setting Up Routes

Go to routes/web.php and add the following route method in it.

Route::get('/','SearchController@index');

Route::get('/search','SearchController@search');

Read More About: Working With Routes In Laravel

Now that everything is ready, go to the application and launch the app using the staging URL.

access-details

You will see the following UI:

Now to test the functionality, carry out a search (you could start with the following example):

As you can see, as I entered W, the search bar started returning results containing the partial matches.

You might also like: Introduction To Laravel Dusk: Testing Todo App

Experience Unparalleled Laravel Hosting performance With Cloudways

Laravel Hosting Taken to the Next Level – Cloudways’ Managed Hosting Offers Unbeatable Speed and Reliability.

Conclusion

Laravel search’s updated search box drastically reduces the chances of visitors bouncing from your site and helps you capture potential clients, making it especially invaluable for businesses. Moreover, Laravel Ajax search serves to improve both client involvement and sales. Accurately implement the ways of using the Laravel search bar feature as outlined in this article, and harness great results!

Q. How do you make a search bar in laravel?

A: Create a new Laravel application with the Laravel CLI and enter the registry with the following commands:

$ laravel new livewire-search && cd livewire-search.
$ composer require livewire/livewire.
$ npx tailwindcss-cli@latest build -o public/css/tailwind.css.
$ php artisan migrate && php artisan db:seed.

Q. How to search function in laravel?

A: The best way to search a function in laravel can be completed within 2 easy steps:

  • Step 1: Modify the index method in the project controller
  • Step 2: add the form that will send the request to the controller in index.blade.php

Q. How do I create a search form in laravel?

A: There are numerous ways of including search functionality to your Laravel site:

  • First, you need to create a controller if you do not have one already.
  • Once our controller is prepared, we need to include a new route within the web.php file.
  • Now, we just need to include a form in our search.blade.php file.

Share your opinion in the comment section. COMMENT NOW

Share This Article

Shahzeb Ahmed

Shahzeb is a Digital Marketer with a Software Engineering background, works as a Community Manager — PHP Community at Cloudways. He is growth ambitious and aims to learn & share information about PHP & Laravel Development through practice and experimentation. He loves to travel and explore new ideas whenever he finds time. Get in touch with him at [email protected]

×

Get Our Newsletter
Be the first to get the latest updates and tutorials.

Thankyou for Subscribing Us!

×

Webinar: How to Get 100% Scores on Core Web Vitals

Join Joe Williams & Aleksandar Savkovic on 29th of March, 2021.

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Want to Experience the Cloudways Platform in Its Full Glory?

Take a FREE guided tour of Cloudways and see for yourself how easily you can manage your server & apps on the leading cloud-hosting platform.

Start my tour

CYBER WEEK SAVINGS

  • 0

    Days

  • 0

    Hours

  • 0

    Mints

  • 0

    Sec

GET OFFER

For 4 Months &
40 Free Migrations

For 4 Months &
40 Free Migrations

Upgrade Now