Debug School

rakesh kumar
rakesh kumar

Posted on

How to renders dynamic data from livewire based on filter condition

Here's how you can modify the Livewire component to use pagination and retrieve data from a specific field in the database table:

// app/Http/Livewire/ExampleComponent.php

namespace App\Http\Livewire;

use Livewire\Component;
use App\Models\ExampleModel;

class ExampleComponent extends Component
{
    public $data;
    public $fieldValue;

    public function mount()
    {
        // Fetch paginated data from the database
        $this->data = ExampleModel::paginate(10); // Change 10 to your desired pagination limit

        // Set the initial field value (you can replace it with your logic to fetch from another table)
        $this->fieldValue = ExampleModel::value('specific_field');
    }

    public function render()
    {
        return view('livewire.example-component');
    }
}
Enter fullscreen mode Exit fullscreen mode

And here's the updated Blade file:

<!-- resources/views/livewire/example-component.blade.php -->

<div x-data="{ items: @entangle('data').defer, fieldValue: '{{ $fieldValue }}', activeFilter: '' }">
    <div class="row">
        <div class="col-md-2">
            <button class="btn btn-primary" x-on:click="activeFilter = 'Filter 1'">Filter 1</button>
        </div>
        <div class="col-md-2">
            <button class="btn btn-primary" x-on:click="activeFilter = 'Filter 2'">Filter 2</button>
        </div>
        <div class="col-md-2">
            <button class="btn btn-primary" x-on:click="activeFilter = 'Filter 3'">Filter 3</button>
        </div>
        <div class="col-md-2">
            <button class="btn btn-primary" x-on:click="activeFilter = 'Filter 4'">Filter 4</button>
        </div>
    </div>

    <template x-if="fieldValue === 'specific_value'">
        <div>
            <h2>Displaying Data</h2>
            <template x-for="item in items.data" :key="item.id" x-show="item.name.includes(activeFilter)">
                <div x-text="item.name"></div>
            </template>
        </div>
        <!-- Pagination Links -->
        <div>
            {{ $data->links() }}
        </div>
    </template>
    <template x-else>
        <div>
            <p>No data to display.</p>
        </div>
    </template>
</div>
Enter fullscreen mode Exit fullscreen mode

In this updated code:

We've replaced ExampleModel::all() with ExampleModel::paginate(10) to fetch paginated data from the database, limiting it to 10 items per page. Adjust the pagination limit (10) to your desired value.
In the Blade file, we're using to render pagination links for the paginated data.
With these changes, your Livewire component will fetch paginated data from the database and pass it to the Blade file, where Alpine.js will handle the filtering functionality as before, but with pagination support.

Top comments (0)