In this tutorial, I will show you how to create a real-time search feature in Laravel 11 using Livewire 3. Livewire makes it easy to build dynamic search functionality without writing complex JavaScript.
We will create a simple search bar that filters results as you type. This is useful for searching products, users, posts, or any data in your application.
Laravel 11 Livewire 3 Search: Step-by-Step Guide
First, install Livewire in your Laravel 11 project if you haven’t already:
composer require livewire/livewire
Then, publish the Livewire configuration:
php artisan livewire:publish
Run the following command to generate a Livewire component:
php artisan make:livewire search-users
This will create two files:
app/Livewire/SearchUsers.php
(Component logic)resources/views/livewire/search-users.blade.php
(Component view)
Open app/Livewire/SearchUsers.php and update the code:
namespace App\Livewire;
use Livewire\Component;
use App\Models\User;
class SearchUsers extends Component
{
public $search = '';
public function render()
{
$users = User::where('name', 'like', '%' . $this->search . '%')->get();
return view('livewire.search-users', compact('users'));
}
}
Here, we use the $search
property to store the search query and dynamically fetch users from the database.
Open resources/views/livewire/search-users.blade.php and add the following code.
<div>
<input type="text" wire:model="search" placeholder="Search users..." class="form-control">
<ul>
@foreach($users as $user)
<li>{{ $user->name }}</li>
@endforeach
</ul>
</div>
The wire:model="search"
binding ensures that as the user types, the search updates in real time
Now, add the component to any Blade view, such as resources/views/welcome.blade.php
@livewire('search-users')
Start your Laravel application:
php artisan serve
You might also like:
Hey there, I recently found myself in a situation where I needed to downgrade my PHP version from 8.2 to 8.1 on my Ubunt...
Nov-01-2023
In this article, we will see the laravel orderBy, groupBy, and limit examples. Here we will see different types of&...
Jan-27-2021
In this article, we will see how to install React in laravel 9. We will also install react with laravel 9 and...
Aug-15-2022
In this article, we will see examples of carbon adding years to date in laravel. Here we will laravel add...
Dec-07-2020