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

$('#exampleTable').DataTable({
    "responsive": true,
    "processing": true,
    "serverSide": true,
    "ajax": {
        "url": "{{ route('fetchUserData') }}",
        "type": "GET",
        "error": function(xhr, status, errorThrown) {
            console.error("Error during AJAX request: ", errorThrown);
        },
        "dataSrc": function(response) {
            console.info("Data received from server: ", response);
            if (response.records && response.records.length) {
                console.info("Data entries loaded:");
                response.records.forEach(function(record) {
                    console.log(record);
                });
                return response.records;
            } else {
                console.warn("No records found.");
                return [];
            }
        }
    },
    "columns": [
        { "data": "username" },
        { "data": "points" },
        { "data": "followers" },
        { "data": "referrals" }
    ],
    "language": {
        "emptyTable": "No records to display" // Custom message for empty table
    },
    "initComplete": function() {
        $('div.dataTables_length select').addClass('form-select mt-1 w-full');
        $('div.dataTables_filter input').addClass('form-input block w-full mt-1');
    },
    "drawCallback": function() {
        $('table').addClass('min-w-full bg-gray-50');
        $('thead').addClass('bg-blue-100');
        $('thead th').addClass('py-3 px-5 text-left text-xs font-semibold text-gray-700 uppercase tracking-wide');
        $('tbody tr').addClass('border-t border-gray-300');
        $('tbody td').addClass('py-3 px-5 text-sm text-gray-800');
    }
});

This JavaScript code initializes a DataTables instance on an HTML table with the ID #exampleTable. It enhances the table with various features like responsiveness, server-side processing, AJAX data fetching, and custom styling.

Oct 24, 2024
Read More
Tutorial

Livewire Cheat Sheet: PHP & JavaScript Tips

  • Capture browser events dispatched from the Livewire PHP side:
   window.addEventListener('eventName', event => {
       console.log('Browser event received:', event.detail);
   });

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!