How to Build a Real-Time Search Box in Laravel Using Livewire
Learn how to build a real-time search box in Laravel using Livewire. This step-by-step tutorial covers setting up Livewire components, handling user input dynamically, and optimizing search performance for a seamless user experience. Perfect for developers looking to enhance their Laravel applications with interactive search functionality.
Laravel

Searching is a crucial feature in modern web applications, and implementing it in real time enhances user experience significantly. In this tutorial, we will build a real-time search box using Laravel and Livewire.

Livewire is a powerful Laravel package that allows you to build dynamic interfaces without writing JavaScript. It simplifies real-time search by handling AJAX requests automatically.

By the end of this tutorial, you will have a functional real-time search box that updates results as the user types.


Prerequisites

Before proceeding, ensure you have the following:

  • Basic knowledge of Laravel
  • Laravel installed on your machine (^9.0 or later)
  • Composer installed
  • Livewire package installed
  • A database setup (MySQL, SQLite, or PostgreSQL)

If you haven't installed Laravel yet, run:

 composer create-project laravel/laravel livewire-search
 

Then, navigate into the project:

 cd livewire-search
 

Install Livewire:

 composer require livewire/livewire
 

 

Now, let's get started!


Step 1: Set Up the Database and Model

For this example, we'll create a simple Product model with a name field that we'll search.

Run the following Artisan command to create the model and migration:

php artisan make:model Product -m

Open the newly created migration file in database/migrations/ and define the products table structure:

 public function up()
{
    Schema::create('products', function (Blueprint $table) {
        $table->id();
        $table->string('name');
        $table->timestamps();
    });
}
 

Run the migration to apply changes to the database:

 php artisan migrate
 

Next, seed the database with dummy product data. Open database/seeders/DatabaseSeeder.php and add:

 

use App\Models\Product;

public function run()
{
    Product::factory(50)->create(); // Generate 50 fake products
}
 

Run the seeder:

php artisan db:seed

 


 

Step 2: Create the Livewire Component

Livewire components consist of a PHP class (handles logic) and a Blade view (handles display).

Create a Livewire component for the search box:

 php artisan make:livewire product-search
 

This will generate:

  • app/Http/Livewire/ProductSearch.php (Logic)
  • resources/views/livewire/product-search.blade.php (UI)

Step 3: Implement the Search Logic

Open app/Http/Livewire/ProductSearch.php and update the class:

namespace App\Http\Livewire;

use Livewire\Component;
use App\Models\Product;

class ProductSearch extends Component
{
    public $query = '';

    public function render()
    {
        $products = Product::where('name', 'like', "%{$this->query}%")->get();

        return view('livewire.product-search', compact('products'));
    }
}
 

Explanation:

  • $query stores the user’s search input.
  • render() fetches products that match the search query.
  • '%{$this->query}%' enables partial matching (like SQL’s LIKE keyword).

Step 4: Build the Search UI

Open resources/views/livewire/product-search.blade.php and add the following code:

<div>
    <input type="text" class="border p-2 w-full" placeholder="Search products..." wire:model="query">

    <ul class="mt-2 border rounded p-2">
        @foreach($products as $product)
            <li class="p-1">{{ $product->name }}</li>
        @endforeach
    </ul>
</div>

 

Explanation:

  • <input> uses wire:model="query", which binds user input to $query in real time.
  • When the user types, render() runs automatically, updating the displayed product list.

Step 5: Display the Component in a View

To use the component, open resources/views/welcome.blade.php (or create a new view) and include:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Livewire Search</title>
    @livewireStyles
</head>
<body>
    <div class="container mx-auto p-4">
        @livewire('product-search')
    </div>
    @livewireScripts
</body>
</html>

 

Explanation:

  • @livewireStyles and @livewireScripts load Livewire assets.
  • @livewire('product-search') embeds the search component in the page.

Step 6: Run the Application

Start the Laravel development server:

php artisan serve
 

Visit http://127.0.0.1:8000 in your browser and test the search functionality.


Bonus: Enhance the UX

1. Add Loading Indicator

Livewire provides wire:loading to show a loading indicator while searching:

<div>
    <input type="text" wire:model="query">
    <div wire:loading>Searching...</div>
    <ul>
        @foreach($products as $product)
            <li>{{ $product->name }}</li>
        @endforeach
    </ul>
</div>
 

 

2. Debounce Input

To prevent excessive queries, delay search requests using wire:model.debounce.500ms="query":

 

<input type="text" wire:model.debounce.500ms="query">

Conclusion

You’ve successfully built a real-time search box in Laravel using Livewire! This approach enhances performance and user experience without writing JavaScript.

Key Takeaways: ✅ Livewire handles real-time updates automatically. ✅ wire:model binds inputs without JavaScript. ✅ wire:loading improves user experience. ✅ debounce prevents excessive database queries.

Start using Livewire in your Laravel apps today! 🚀

#Laravel #Livewire #PHP #WebDevelopment

Author: moses on 10-02-2025
Related Posts
Built by codecontent.pro in partnership with Laraveldev.pro
© 2025 Laraveldev.pro