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.

Related Posts

More content you might like

Tutorial
javascript

JavaScript in Modern Web Development

JavaScript is the engine behind the dynamic behavior of modern websites. It works alongside HTML (structure) and CSS (style) to create a complete web experience.

  • JavaScript enables features like dropdown menus, modal windows, sliders, and real-time updates.
  • Examples: Search suggestions, form validations, chat applications.

Dec 10, 2024
Read More
Code
javascript

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

  • serverSide: true enables server-side pagination, sorting, and filtering.
  • processing: true displays a processing indicator while fetching data.
  • The ajax object defines how data is fetched from the server.
  • url: Endpoint for fetching data.
  • type: HTTP method (GET).
  • error: Logs errors that occur during the AJAX request.
  • dataSrc: Processes the server's response. It logs the data and returns records for display.

Oct 24, 2024
Read More
Tutorial

Livewire Cheat Sheet: PHP & JavaScript Tips

  • Call Livewire's file upload from the JavaScript side:
   document.querySelector('input[type="file"]').addEventListener('change', function (e) {
       Livewire.upload('uploadName', this.files[0], (uploadedFilename) => {
           console.log('File uploaded:', uploadedFilename);
       });
   });

Oct 24, 2024
Read More
Tutorial
javascript

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

  • نستخدم $('#myButton') لتحديد الزر الذي يحتوي على المعرف myButton.
  • نستخدم .click() لتحديد حدث "click" الذي سيحدث عند النقر على الزر.
  • عندما يتم النقر، يتم عرض رسالة تحذيرية (alert).

يمكنك استخدام jQuery للتفاعل مع عناصر HTML وتعديلها بسهولة. يمكنك تغيير النصوص، إضافة فئات CSS، إخفاء العناصر، والمزيد.

Sep 26, 2024
Read More

Discussion 0

Please sign in to join the discussion.

No comments yet. Be the first to share your thoughts!