Debug School

rakesh kumar
rakesh kumar

Posted on • Updated on

Livewire component for real-time search/filtering of users

If you already have a UserController with associated Blade views for user management, and you want to integrate Livewire for enhanced interactivity, you can do so by adding Livewire components for specific features. Below is an example of how you could integrate Livewire into your existing setup:

UserController.php: This controller will handle the basic CRUD operations for users.

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;

class UserController extends Controller
{
    public function index()
    {
        $users = User::all();
        return view('users.index', compact('users'));
    }

    // Other CRUD methods
}
Enter fullscreen mode Exit fullscreen mode

users/index.blade.php: This Blade view will display a list of users with basic information and include buttons for editing and deleting users.

<!-- resources/views/users/index.blade.php -->

@extends('layouts.app')

@section('content')
    <div class="container">
        <h2>User Management</h2>

        <div class="row">
            <div class="col-md-12">
                <table class="table">
                    <thead>
                        <tr>
                            <th>Name</th>
                            <th>Email</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach ($users as $user)
                            <tr>
                                <td>{{ $user->name }}</td>
                                <td>{{ $user->email }}</td>
                                <td>
                                    <a href="{{ route('users.edit', $user->id) }}" class="btn btn-primary">Edit</a>
                                    <form action="{{ route('users.destroy', $user->id) }}" method="POST" style="display: inline;">
                                        @csrf
                                        @method('DELETE')
                                        <button type="submit" class="btn btn-danger">Delete</button>
                                    </form>
                                </td>
                            </tr>
                        @endforeach
                    </tbody>
                </table>
            </div>
        </div>
    </div>
@endsection
Enter fullscreen mode Exit fullscreen mode

Integrating Livewire: Let's say you want to add a feature for real-time search/filtering of users. You can create a Livewire component for this purpose.

php artisan make:livewire UserSearch
Enter fullscreen mode Exit fullscreen mode

UserSearch.php: This Livewire component will handle the search functionality.

namespace App\Http\Livewire;

use Livewire\Component;
use App\Models\User;

class UserSearch extends Component
{
    public $search;

    public function render()
    {
        $users = User::where('name', 'like', '%' . $this->search . '%')
                     ->orWhere('email', 'like', '%' . $this->search . '%')
                     ->get();

        return view('livewire.user-search', ['users' => $users]);
    }
}
Enter fullscreen mode Exit fullscreen mode

livewire/user-search.blade.php: This is the view for the Livewire component that will render the search results.

<!-- resources/views/livewire/user-search.blade.php -->

<div>
    <input type="text" wire:model="search" placeholder="Search by name or email...">

    <ul>
        @foreach ($users as $user)
            <li>{{ $user->name }} - {{ $user->email }}</li>
        @endforeach
    </ul>
</div>
Enter fullscreen mode Exit fullscreen mode

Update users/index.blade.php: Add the Livewire component to your existing Blade view to render the search feature.

<!-- resources/views/users/index.blade.php -->

@extends('layouts.app')

@section('content')
    <div class="container">
        <h2>User Management</h2>

        <!-- Livewire User Search Component -->
        @livewire('user-search')

        <div class="row">
            <div class="col-md-12">
                <table class="table">
                    <!-- Table Headers and User Data Rows -->
                </table>
            </div>
        </div>
    </div>
@endsection
Enter fullscreen mode Exit fullscreen mode

With this setup, your UserController handles the basic CRUD operations, and you've integrated a Livewire component (UserSearch) for real-time search/filtering of users. You can expand on this by adding more Livewire components for additional features as needed.

Display data with pagination and filter

here's an example code to display data fetched from the database using Livewire's mount method with pagination:

<?php

namespace App\Http\Livewire;

use Livewire\Component;
use App\Models\YourModel; // Replace YourModel with your actual model name
use Livewire\WithPagination;

class YourComponent extends Component
{
    use WithPagination;

    public $perPage = 10;
    public $filter = '';

    public function mount()
    {
        $this->loadData();
    }

    public function loadData()
    {
        $this->posts = YourModel::where(function ($query) {
            if (!empty($this->filter)) {
                $query->where('title', 'like', '%' . $this->filter . '%')
                      ->orWhere('content', 'like', '%' . $this->filter . '%');
            }
        })->paginate($this->perPage);
    }

    public function updatedFilter()
    {
        $this->resetPage(); // Reset pagination when filter changes
        $this->loadData(); // Reload data with updated filter
    }

    public function render()
    {
        return view('livewire.your-component', [
            'posts' => $this->posts, // Pass the fetched data to the view
        ]);
    }
}
Enter fullscreen mode Exit fullscreen mode

In this code:

We use the WithPagination trait provided by Livewire to handle pagination.
In the mount method, we fetch data from the database using your model (YourModel), and paginate it based on the specified number of items per page ($this->perPage).
The fetched data is passed to the view using the render method.
In your Blade view (your-component.blade.php), you can iterate over the $posts variable to display the data.
Here's how you can display the paginated data in your Blade view:

<div>
    <!-- Display paginated data -->
    @foreach ($posts as $post)
        <!-- Display individual post data here -->
        <p>{{ $post->title }}</p>
        <p>{{ $post->content }}</p>
    @endforeach

    <!-- Display pagination links -->
    {{ $posts->links() }}
</div>
Enter fullscreen mode Exit fullscreen mode

Make sure to replace with the actual name of your model, and adjust the code accordingly based on your database structure and requirements.

Top comments (0)