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

  • language.emptyTable: Custom message displayed when no data is available.
  • initComplete: Adds custom classes to dropdowns and inputs in the DataTables UI for consistent styling.

Oct 24, 2024
Read More
Tutorial

Livewire Cheat Sheet: PHP & JavaScript Tips

  • In Blade:
   <button wire:click="$emit('buttonClicked')">Click Me</button>

Oct 24, 2024
Read More
Tutorial
javascript

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

يمكنك أيضًا تنزيل jQuery واستضافة الملف محليًا في مشروعك:

<script src="path/to/jquery.min.js"></script>

Sep 26, 2024
Read More
Tutorial
javascript

AJAX with JavaScript: A Practical Guide

In many real-world applications, you'll need to send data to the server using POST requests. Here's how to send form data using the Fetch API.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>POST Request with Fetch</title>
</head>
<body>
    <form id="postDataForm">
        <input type="text" id="title" placeholder="Enter title" required>
        <input type="text" id="body" placeholder="Enter body" required>
        <button type="submit">Submit</button>
    </form>
    <div id="postDataOutput"></div>

    <script>
        document.getElementById('postDataForm').addEventListener('submit', function(e) {
            e.preventDefault();

            const title = document.getElementById('title').value;
            const body = document.getElementById('body').value;

            fetch('https://jsonplaceholder.typicode.com/posts', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    title: title,
                    body: body
                })
            })
            .then(response => response.json())
            .then(data => {
                document.getElementById('postDataOutput').innerHTML = `
                    <h3>Data Submitted:</h3>
                    <p>Title: ${data.title}</p>
                    <p>Body: ${data.body}</p>
                `;
            })
            .catch(error => console.error('Error:', error));
        });
    </script>
</body>
</html>

Sep 18, 2024
Read More
Tutorial
javascript php

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

    namespace App\Http\Livewire;

    use Livewire\Component;

    class EditorComponent extends Component
    {
        public $content = '';

        protected $listeners = ['updateContent'];

        public function updateContent($wireId, $newContent)
        {
            $this->content = $newContent;
        }

        public function render()
        {
            return view('livewire.editor-component');
        }
    }

Here, we’ve defined a content property to store the editor’s content. The updateContent method listens for updates from the front-end and sets the content accordingly.

Aug 14, 2024
Read More
Tutorial
php

Dynamically Updating Form Fields with Livewire in Laravel

When building dynamic forms in Laravel, Livewire makes it easy to update form fields in real-time based on user interactions without needing to reload the page. In this tutorial, we'll walk through how to create a dynamic form where the options in a dropdown field are updated based on the selection of another field.

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

Aug 14, 2024
Read More
Tutorial
javascript php

Managing Modals with Livewire and JavaScript

<?php

namespace App\Http\Livewire;

use Livewire\Component;

class ModalManager extends Component
{
    public function openUserProfileModal()
    {
        $this->dispatchBrowserEvent('open-modal', ['modalId' => 'user-profile-modal']);
    }

    public function openSettingsModal()
    {
        $this->dispatchBrowserEvent('open-modal', ['modalId' => 'settings-modal']);
    }

    public function openNotificationsModal()
    {
        $this->dispatchBrowserEvent('open-modal', ['modalId' => 'notifications-modal']);
    }

    public function render()
    {
        return view('livewire.modal-manager');
    }
}

Modify your Livewire component's Blade view to call the methods defined in the component class.

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!