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.

[WEBINAR: April 29] Learn How To Take Control of Cloudflare Enterprise on Cloudways. Register Now→

How to Build a Live Search Feature in Laravel with AJAX

Updated on September 22, 2025

15 Min Read
laravel search bar

Key Takeaways

  • AJAX is the foundation of live search. It allows the front end to send and receive data from the server without a full page refresh.
  • Live search requires a full-stack approach. You need a working database, a model, a controller to handle the logic, a view for the user interface, and routes to connect them all.
  • Since live search runs on every keystroke, optimizing your database queries (using indexes, limiting results, or debouncing requests) is essential to keep the feature fast and responsive.

Live search has become a must-have feature on modern websites, helping users find what they need instantly without waiting for a page to reload. As you type, results appear right away — creating a smooth, fast experience that keeps people engaged.

This real-time magic is powered by AJAX, which quietly sends search requests to the server in the background and fetches matching results without disrupting the page.

In this tutorial, we’ll build a live search feature from scratch using Laravel. You’ll see how to connect the database, model, controller, view, and routes to make it work — and once it’s running locally, we’ll also deploy it to a live Cloudways server so your app can be accessed online.

What Is AJAX and Why Does It Matter for Live Search?

AJAX, which stands for Asynchronous JavaScript and XML, is the technology that makes live search possible without a full page reload. In simple terms, AJAX allows a web page to communicate with the server in the background without interrupting what the user is doing.

When you type in a live search box, the browser uses AJAX to send a small request to the server, which then returns the search results. All of this happens behind the scenes, so the results simply appear on the page.

This asynchronous communication provides instant feedback, creating a faster and more intuitive experience for the user.

In this tutorial, we’re going to build a live search feature in Laravel. When a user types into a search box, results appear immediately, without refreshing the page.

By the end of this guide, you’ll have a working live search system for your products, blog posts, or any dataset you choose.

We’ll do this step by step, so even if you’re new to Laravel, PHP, or databases, you can follow along and understand what’s happening at each stage.

Step 1: Prerequisites
Step 2: What We’re Building
Step 3: Setting Up the Database
Step 4: Creating a New Laravel Project
Step 5: Configuring the Database
Step 6: Creating the Products Table
Step 7: Populating the Table with Dummy Data
Step 8: Creating the Controller
Step 9: Creating the View
Step 10: Setting Up Routes
Step 11: Testing the Live Search

For this tutorial, I’ll be using:

  • Windows machine
  • XAMPP (for Apache + MySQL)
  • CMD (Command Prompt) for running Laravel commands

These choices are just for demonstration. I’m using Windows + XAMPP because it’s a common setup that many people can try on their own machine.

Step 1: Prerequisites

Before we start coding, make sure you have the following installed:

  1. PHP 8.x or higher – Laravel needs PHP to run.
  2. Composer – Laravel’s dependency manager. You can get it from getcomposer.org.
  3. Laravel 12.x – The version we’ll use in this tutorial.
  4. MySQL (via XAMPP) – To store our product data.
  5. A code editor – VS Code or any editor you prefer.
  6. CMD (or PowerShell) – We’ll run all Laravel commands from here.

For this tutorial, I’ll show commands and file edits using my Windows + XAMPP setup. If you’re on Mac or Linux, paths and commands may differ slightly, but the steps remain the same.

Step 2: What We’re Building

Here’s exactly what we’re building in this blog:

  • A products table in MySQL with some demo data.
  • A Laravel page with a search input box.
  • When a user types in the box, matching products are shown instantly below, without reloading the page.

That’s it. Simple, practical, and exactly what you came here to learn: how to create a live search feature in Laravel using AJAX.

Step 3: Setting Up the Database

First, let’s prepare the database where our products will live:

  • Open XAMPP and start Apache and MySQL.

start Apache and MySQL on Xampp

Open phpMyAdmin

  • Create a new database called:
live_search_db

Create a new database

  • For modern web development, it’s best practice to use a UTF-8 collation like utf8mb4_general_ci.
  • Hit the Create button.

This will create a database to store our product records. You can call it anything, just remember the name because we’ll need it in the .env file later.

create a database to store product records

Step 4: Creating a New Laravel Project

Now we’ll create a new Laravel project using Composer:

  • Open CMD and navigate to your XAMPP projects folder. For example:

cd C:\xampp\htdocs

XAMPP projects folder

  • Run the following command to create a new Laravel project called live-search:
composer create-project laravel/laravel live-search

laravel live-search

  • Once it’s done, navigate into the project folder:
cd live-search

cd live-search

At this point, we have a blank Laravel project ready to go. Think of this as our canvas—we’ll now start building the live search feature on top of it.

Step 5: Configuring the Database

Now that we have our database ready, we need to connect our Laravel project to it. We do this by editing the .env file, which is located in your project’s root folder. This file holds all the essential configuration settings for your application.

Open the .env file and look for the database section. My .env file is at this path: C:\xampp\htdocs\live-search.

Open the .env file for database section

DB_CONNECTION=mysql

DB_HOST=127.0.0.1

DB_PORT=3306

DB_DATABASE=live_search_db

DB_USERNAME=root

DB_PASSWORD=

You’ll need to update it with the following details:

DB_CONNECTION=mysql — This tells Laravel that we’re using a MySQL database.

DB_HOST=127.0.0.1 — This is the local address where our XAMPP server is running.

DB_PORT=3306 — This is the default port for MySQL.

DB_DATABASE=live_search_db — This is the name of the database we just created.

DB_USERNAME=root — This is the default username for MySQL in XAMPP.

DB_PASSWORD= — The default password for the root user is empty, so we’ll leave this blank.

Update the database details

Once you’ve saved these changes, Laravel will know exactly where to store and fetch all our product data. The next step is to create the actual products table inside our new database.

Now Laravel knows where to store and fetch our products. The next step is to create the products table.

Step 6: Creating the Products Table

Now that our project is connected to the database, we need to create a table to store our products. In Laravel, we do this using a migration, which is like a version control system for your database schema.

First, go back to your command prompt or terminal and run the following command. This will generate a new migration file for our products table.

php artisan make:migration create_products_table

migration create_products_table

  • Next, open the new file located in the database/migrations/ folder.

Database Migration Folder

  • Replace the up() function with:
public function up()

{

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

$table->id();

$table->string('title');

$table->string('description');

$table->decimal('price', 10, 2);

$table->timestamps();

});

}

Replace the up() function

We’re replacing the existing code in this function to specify the columns we need for our products:

$table->id(): This creates an auto-incrementing primary key for our table, which will uniquely identify each product.

$table->string(‘title’): This adds a column for the product’s title.

$table->string(‘description’): This adds a column for the product’s description.

$table->decimal(‘price’, 10, 2): This creates a column to store the price with a precise number of decimal places.

$table->timestamps(): This adds two columns, created_at and updated_at, which Laravel will automatically manage for us.

After you’ve replaced the code in the up() function, save the file. Now we can run the migration to apply these changes to our database and create the table.

php artisan migrate

php artisan migrate

When you run this command, Laravel will execute the code in your up() function, creating the products table in your live_search_db database.

You can confirm this by checking phpMyAdmin, where you’ll see your new table with all the columns we just defined.

products table in live_search_db database

Step 7: Populating the Table with Dummy Data

Now that our table is ready, we need to add some products to it so we have something to search for. The best way to do this in Laravel is by using a Seeder. This is a file that lets you easily populate your database with fake or test data.

First, let’s create a new Seeder file by running this command in your terminal:

php artisan make:seeder ProductSeeder

seeder ProductSeeder

This will create a new file at database/seeders/ProductSeeder.php. Open this file and replace the existing run() function with the code below. This code will insert five different products—like a T-shirt, jeans, and a laptop—into our new table.

use Illuminate\Database\Seeder;

use Illuminate\Support\Facades\DB;




class ProductSeeder extends Seeder

{

/**

* Run the database seeds.

*

* @return void

*/

public function run()

{

DB::table('products')->insert([

[

'title' => 'T-shirt',

'description' => 'A comfortable cotton t-shirt.',

'price' => 15.00,

],

[

'title' => 'Jeans',

'description' => 'Classic blue denim jeans.',

'price' => 45.50,

],

[

'title' => 'Laptop',

'description' => 'Powerful laptop for all your needs.',

'price' => 1200.00,

],

[

'title' => 'Keyboard',

'description' => 'Mechanical keyboard with RGB lighting.',

'price' => 75.25,

],

[

'title' => 'Mouse',

'description' => 'Ergonomic wireless mouse.',

'price' => 30.00,

]

]);

}

}

After you save the file, we need to tell Laravel to run this seeder. Open the main DatabaseSeeder.php file (also in the database/seeders folder) and add this line inside the run() function:

$this->call(ProductSeeder::class);

DatabaseSeeder.php file

Finally, go back to your terminal and run the main seed command. This will execute our ProductSeeder and fill the products table with the dummy data.

php artisan db:seed

Seeding Database

You can now check the products table in phpMyAdmin to see all the new entries.

Check new entries in products table in phpMyAdmin

Step 8: Creating the Controller

Now that our database has some dummy data, we need to create a controller to manage the logic for our search page. Think of a controller as the “middleman” of your application. It takes a request from your website, figures out what to do with it, and sends a response back.

In our case, we want the controller to handle two things: displaying the search page and processing the search queries. We’ll set up two separate functions inside the controller to manage this.

To create it, just run this command in your terminal:

php artisan make:controller SearchController

Controller searchcontroller

This will automatically create a new file for us at app/Http/Controllers/SearchController.php. Now, open that file and replace its contents with the code below.

The code contains two main parts:

index(): This function is straightforward. Its only job is to show the user the search page.

search(): This function handles the live search requests. It takes whatever the user types, searches for matching products in the database, and then sends the results back to the page. It also includes input validation to keep things safe and secure.

<?php




namespace App\Http\Controllers;




use Illuminate\Http\Request;

use App\Models\Product;




class SearchController extends Controller

{

public function index()

{

// This will show the search page

return view('search.search');

}




public function search(Request $request)

{

$request->validate([

'search' => 'nullable|string|max:255'

]);




if($request->ajax()) {

$products = Product::where('title', 'like', '%' . $request->search . '%')->get();

$output = '';

if($products->count() > 0) {

foreach($products as $product) {

$output .= '<tr>'.

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

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

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

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

'</tr>';

}

} else {

$output .= '<tr><td colspan="4">No results found</td></tr>';

}

return response($output);

}

}

}

Step 9: Creating the View

Now that our controller is ready, it’s time to build the user interface. This is what the user will actually see and interact with. In Laravel, the front end is built using Views.

First, create a new folder named search inside the resources/views/ directory. Then, inside that new folder, create a file called search.blade.php.

Next, add the code below into your new search.blade.php file.

<!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/3.6.0/jquery.min.js"></script>

</head>

<body>

<div class="container mt-5">

<h3>Products Info</h3>

<input type="text" class="form-control" id="search" placeholder="Search products...">

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

<thead>

<tr>

<th>ID</th>

<th>Product Name</th>

<th>Description</th>

<th>Price</th>

</tr>

</thead>

<tbody></tbody>

</table>

</div>




<script>

$.ajaxSetup({

headers: {

'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')

}

});




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

let query = $(this).val();

$.ajax({

type: 'GET',

url: '{{ url("search") }}',

data: {search: query},

success: function(data){

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

}

});

});

</script>

</body>

</html>

This code includes the HTML structure for our search page and some JavaScript to handle the live search functionality.

Here’s a quick look at what the code does:

The HTML sets up a simple page with a search bar and a table to display the results.

The meta name=”_token” is crucial for security. It helps protect your application from cross-site request forgery (CSRF) attacks.

The JavaScript code uses jQuery to listen for what a user types into the search bar. Every time a key is pressed, it sends an AJAX request to your SearchController, which then returns the matching products.

Once you have this file saved, we’ll be ready for the final step: linking this view to the controller using routes.

Step 10: Setting Up Routes

This is the final step in our setup. We need to create routes to tell Laravel how to connect a URL with our new SearchController. Routes act like a map for your application, guiding requests from the user’s browser to the correct controller function.

Open the routes/web.php file and add the following code:

use App\Http\Controllers\SearchController;




Route::get('/', [SearchController::class, 'index']);

Route::get('/search', [SearchController::class, 'search']);

SearchController

Here’s what these two lines do:

Route::get(‘/’, …): This connects the homepage (/) of your application to the index() function in our SearchController. So, when someone visits your main URL, they’ll see the search page you just created.

Route::get(‘/search’, …): This route is for our live search functionality. It connects the /search URL to the search() function in our controller. The JavaScript on our search page will send all its requests to this route.

That’s it! Now your application knows how to handle the search page and the live search requests.

Step 11: Testing the Live Search

To see your live search in action, you need to start the Laravel development server. Go to your terminal and run the following command:

php artisan serve

Next, open your web browser and navigate to http://127.0.0.1:8000/. You should see the search page you created.

Now, simply start typing the name of a product, like “Laptop” or “T-shirt,” into the search bar. As you type, you’ll see the results appear instantly below the search box, thanks to the live search functionality we built.

Live search functionality

Congratulations! You’ve successfully built a live search feature in Laravel. You can now explore more advanced features like searching multiple columns or adding more styling to the results.

Earlier, we built a live search feature in Laravel on a local environment to test how it works. Now, let’s take it a step further and deploy that same Laravel project on a real server so it’s accessible online.

Step 1: Create a Cloudways Account
Step 2: Spin Up a New Server
Step 3: Locate Your Laravel App on the Server
Step 4: Prepare Your Laravel Project to Move to Cloudways Server
Step 5: Upload the Project via FileZilla
Step 6: Export Your Local Database
Step 7: Import Your Database to Cloudways
Step 8: Configure Laravel on the Server
Step 9: Verify Your Laravel App on Cloudways

In this guide, I’ll walk you through hosting your Laravel live search app on Cloudways — from setting up the server to uploading your project and configuring it to work seamlessly in a production environment.

Step 1: Create a Cloudways Account

Go to the Cloudways website and register for a free account (they offer a 3-day trial, no credit card needed). Once you log in, you’ll land on your Cloudways dashboard.

Step 2: Spin Up a New Server

Click on “Add Server” and fill in the details like this

  • Application: Select Laravel (Cloudways will handle the initial setup for you)
  • Name: Call it something like laravel-search
  • Cloud Provider: Pick DigitalOcean
  • Server Size: Start with 1GB for now (you can upgrade later)
  • Region: Choose a location close to your target users

Click “Launch Now”. In a few minutes, Cloudways will create a fresh Laravel-ready server for you.

Step 3: Locate Your Laravel App on the Server

After the server finishes launching:

  1. Go to the Applications tab inside your Cloudways dashboard.
  2. Click on the Laravel app you just created.
  3. Open the Application URL.

Right now, you’ll see Cloudways’ default welcome page and not Laravel’s default page. That’s normal — we still need to upload your actual project files to replace it.

Step 4: Prepare Your Laravel Project to Move to Cloudways Server

On your local machine, go to the laravel project folder we created earlier called “live-search”.

Live search project

Before sending it to the server, delete these two items:

  • The vendor/ folder (it’s large and can be rebuilt on the server)
  • The .env file (we’ll generate a new one with the correct server credentials)

delete these items

As you can see, I’ve deleted both vendons/ and .env file in the screenshot above.

Step 5: Upload the Project via FileZilla

Now let’s move your project to the Cloudways server.

  • Get your SFTP credentials from the Cloudways dashboard under Servers Master Credentials.
  • Open FileZilla and connect using the provided IP, username, password, and port (22).
  • Now go to:

/applications/[your_app_username]/public_html

  • On the left side (your PC), open your live-search folder.
  • Drag all the files (except vendor/ and .env) from your live-search folder to public_html on the server.

This uploads your Laravel project to the server.

Step 6: Export Your Local Database

Before configuring Laravel on the server, you need to take your local database (we created this on phpMyAdmin called live_search_db) and move it to Cloudways.

Here’s how:

Export tab

  • Finally click the Export button. Make sure the format you download the file in is SQL.

This will download a .sql file to your computer — this contains all your tables and products.

download a .sql file

Step 7: Import Your Database to Cloudways

Now let’s get that .sql file into your Cloudways server.

  • In the Cloudways dashboard, go to your Laravel application.
  • Click Launch Database Manager to launch it.

 Launch Database Manager

  • Inside the Database Manager, click the Import tab.

click the Import tab inside database manager

  • Upload the .sql file you just exported and click Import.

Upload the .sql file

Once done, your Cloudways database will now contain the same tables and data as your local setup.

Step 8: Configure Laravel on the Server

Now it’s time to set up Laravel to use the database you just imported.

First, open the SSH Terminal from your Cloudways dashboard and log in using your Master Credentials.

Once you’re in, move into your Laravel project folder and install all the dependencies:

cd applications/[your_app_username]/public_html

composer install

Next, create a fresh environment file that Laravel will use for all your app settings:

cp .env.example .env

Before we configure it, let’s generate the unique app key (this is what Laravel uses to keep sessions and encrypted data secure):

php artisan key:generate

With that done, open the .env file to plug in your database credentials:

nano .env

Inside .env, update these values (you’ll find the database details in your Application Credentials section on Cloudways):

DB_CONNECTION=mysql

DB_HOST=127.0.0.1

DB_PORT=3306

DB_DATABASE=your_db_name

DB_USERNAME=your_db_username

DB_PASSWORD=your_db_password




APP_URL=https://your-cloudways-app-url

APP_DEBUG=false

update DB values inside .env

Save the file (Ctrl + X, then Y, and Enter).

Step 9: Verify Your Laravel App on Cloudways

With everything set up, it’s time to make sure your app is actually working on the live server.

Here’s how:

  • Go to your Cloudways dashboard
  • Open the Applications tab
  • Click on your Application URL

Application URL

This will open your site in the browser. If your database was imported correctly and your .env is configured, you should now see your Laravel live search app running on the server — just like it worked locally, but live on the web.

Conclusion

This is it! You’ve successfully built and deployed a live search feature in Laravel, taking it from a local development environment all the way to a live server.

By completing this tutorial, you’ve gained practical experience with several core concepts:

  • Database Management: Setting up and migrating a database.
  • Backend Logic: Creating a controller to handle requests.
  • Frontend Interaction: Using AJAX to create a dynamic user experience.
  • Deployment: Moving your Laravel app to a professional hosting platform.

Now that you have a working live search system, the possibilities are endless. You can expand its functionality by adding more features like searching across multiple columns, implementing filtering options, or improving the design with more advanced CSS.

If you still have any questions, let me know in the comments.

Frequently Asked Questions

1. What is the benefit of adding live search to a Laravel application?
Live search makes your site more user-friendly by showing results instantly as users type. It reduces page reloads, speeds up navigation, and improves the overall user experience — especially on content-heavy or eCommerce sites.

2. Why host a Laravel project on Cloudways instead of shared hosting?
Cloudways offers managed cloud hosting that’s faster and more scalable than typical shared hosting. You get a dedicated environment, built-in caching, SSH access, easy SFTP uploads, and one-click server scaling — all of which make it ideal for running a production-ready Laravel app.

3. Does implementing live search affect website performance?
It can if done inefficiently, since live search makes frequent requests to the server. However, when implemented properly — with techniques like query throttling, caching, and indexing your database — it has minimal impact and can actually improve perceived performance by giving users faster access to information.

Share your opinion in the comment section. COMMENT NOW

Share This Article

Abdul Rehman

Abdul is a tech-savvy, coffee-fueled, and creatively driven marketer who loves keeping up with the latest software updates and tech gadgets. He's also a skilled technical writer who can explain complex concepts simply for a broad audience. Abdul enjoys sharing his knowledge of the Cloud industry through user manuals, documentation, and blog posts.

×

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