DeveloperBreeze

Implementing Real-Time Search with Livewire in Laravel

Adding real-time search functionality to your Laravel application can greatly enhance the user experience by allowing users to see search results instantly as they type. In this tutorial, we'll walk through how to build a live search feature using Livewire in Laravel.

Prerequisites

  • Basic understanding of Laravel and Livewire
  • A Laravel project with Livewire installed

Objective

We'll create a real-time search form that filters and displays results as the user types in the search input field.

Step 1: Setting Up the Livewire Component

First, let's create a Livewire component to handle our search functionality.

Component Class

Run the following command to generate a Livewire component:

php artisan make:livewire SearchPosts

Open the newly created SearchPosts.php file and set up the properties and methods to manage the search query and results:

<?php

namespace App\Http\Livewire;

use Livewire\Component;
use App\Models\Post;

class SearchPosts extends Component
{
    public $query = '';
    public $posts = [];

    public function updatedQuery()
    {
        $this->posts = Post::where('title', 'like', '%' . $this->query . '%')->get();
    }

    public function render()
    {
        return view('livewire.search-posts');
    }
}

Step 2: Creating the Blade View

Next, create the Blade view for this component in resources/views/livewire/search-posts.blade.php.

Blade Template

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

    <!-- Search Results -->
    @if(!empty($posts))
        <ul class="mt-4">
            @foreach($posts as $post)
                <li class="p-2 border-b">{{ $post->title }}</li>
            @endforeach
        </ul>
    @elseif(strlen($query) > 0)
        <p class="mt-4 text-gray-500">No results found for "{{ $query }}".</p>
    @endif
</div>

Step 3: Updating the Routes

Ensure your Livewire component is properly routed. Add the following to your web.php file:

use App\Http\Livewire\SearchPosts;

Route::get('/search-posts', SearchPosts::class);

Step 4: Testing the Search Functionality

Navigate to http://your-app-url/search-posts in your browser. Start typing in the search input field, and you should see the search results update in real-time.

Explanation

  • Search Query Binding: The query property is bound to the search input field. As the user types, the updatedQuery method is triggered.
  • Dynamic Search: The updatedQuery method performs a search on the Post model using a like query and updates the posts property with the results. The results are then rendered dynamically in the view.
  • Livewire Reactivity: Livewire automatically handles the reactivity, updating the search results as the query property changes without the need for a full page reload.

Conclusion

With Livewire, adding real-time search functionality to your Laravel application is straightforward and efficient. This tutorial showed how to create a live search feature, providing instant feedback to users as they type, enhancing the overall user experience.

Continue Reading

Discover more amazing content handpicked just for you

Tutorial
javascript

JavaScript in Modern Web Development

  • With Node.js, JavaScript powers the back-end to handle databases, APIs, and server logic.
  • Examples: REST APIs, real-time collaboration tools like Google Docs.

JavaScript isn't limited to the browser anymore. It's being used in diverse domains:

Dec 10, 2024
Read More
Code
javascript

Dynamic and Responsive DataTable with Server-Side Processing and Custom Styling

No preview available for this content.

Oct 24, 2024
Read More
Tutorial

Livewire Cheat Sheet: PHP & JavaScript Tips

   Livewire.emit('refreshComponent');
  • Target a specific component for an event:

Oct 24, 2024
Read More
Tutorial
javascript

مكتبة jQuery: استخدام JavaScript بسهولة وفعالية

أبسط طريقة هي استخدام شبكة توزيع المحتوى (CDN) لتحميل jQuery.

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

Sep 26, 2024
Read More
Tutorial
javascript

AJAX with JavaScript: A Practical Guide

In this guide, we'll explore how AJAX works, the basics of making AJAX requests using vanilla JavaScript, and some real-world examples to help you implement AJAX in your own projects.

  • Basic knowledge of HTML, CSS, and JavaScript.
  • Familiarity with JSON (JavaScript Object Notation) as a format for exchanging data.

Sep 18, 2024
Read More
Tutorial
javascript php

Managing WYSIWYG Editors with Livewire: A Step-by-Step Guide

    <div>
        <div wire:ignore>
            <div class="custom-editor" data-wire-id="{{ $this->id }}"></div>
        </div>

        <input type="hidden" wire:model="content">
    </div>

The wire:ignore directive tells Livewire to ignore this section, allowing JavaScript to manage the WYSIWYG editor. We’ve also added a hidden input field bound to the content property, which will hold the editor’s content.

Aug 14, 2024
Read More
Tutorial
php

Dynamically Updating Form Fields with Livewire in Laravel

  • Basic understanding of Laravel and Livewire
  • A Laravel project with Livewire installed

We'll create a form where the available options in a second dropdown field depend on the selection made in the first dropdown field.

Aug 14, 2024
Read More
Tutorial
javascript php

Managing Modals with Livewire and JavaScript

We'll create a system to open and close modals using Livewire and JavaScript by dispatching custom events.

Create a Livewire component, or use an existing one where you want to manage modals.

Aug 14, 2024
Read More
AI Chat 1
Tailwind Component

AI Chat 1

No preview available for this content.

Jan 26, 2024
Read More

Discussion 0

Please sign in to join the discussion.

No comments yet. Start the discussion!