DEV Community

Dendi Handian
Dendi Handian

Posted on • Updated on

Making DataTable-Like Livewire Component: Search Items

Creating Livewire Component and View File

php artisan livewire:make ProductsTable
Enter fullscreen mode Exit fullscreen mode
- app\Http\Livewire\ProductsTable.php
- resources\views\livewire\products-table.blade.php
Enter fullscreen mode Exit fullscreen mode

ProductsTable Component

<?php

namespace App\Http\Livewire;

use App\Models\Product;
use Livewire\Component;

class ProductsTable extends Component
{
    public $search = '';

    public function render()
    {
        $products = !empty($this->search) ? Product::where('name', 'like', '%'.$this->search.'%')->get() : Product::all();
        return view('livewire.products-table', compact('products'));
    }
}

Enter fullscreen mode Exit fullscreen mode

products-table.blade.php view

<div class="w-full min-h-screen p-8">
    <div class="flex justify-center w-full">
        <div class="flex justify-end w-2/3 pb-8">
            <input class="px-2 text-sm border border-gray-300 rounded shadow" wire:model="search" type="text" placeholder="Search Product">
        </div>
    </div>
    <div class="flex justify-center w-full">
        <table class="w-2/3 border border-collapse border-gray-800 shadow">
            <thead>
                <tr>
                    <th class="p-2 text-sm text-gray-500 bg-white border border-gray-300">Name</th>
                    <th class="p-2 text-sm text-gray-500 bg-white border border-gray-300">Created At</th>
                    <th class="p-2 text-sm text-gray-500 bg-white border border-gray-300">Action</th>
                </tr>
            </thead>
            <tbody>
                @foreach ($products as $product)
                    <tr>
                        <td class="p-2 text-sm bg-white border border-gray-300 text-gray">{{ $product->title }}</td>
                        <td class="p-2 text-sm text-center bg-white border border-gray-300 text-gray">{{ $product->created_at->toDateTimeString() }}</td>
                        <td class="p-2 text-sm text-center bg-white border border-gray-300 text-gray">-</td>
                    </tr>
                @endforeach
            </tbody>
        </table>
    </div>
</div>

Enter fullscreen mode Exit fullscreen mode

Usage in products/index.blade.php view

<x-app-layout>
    <x-slot name="header">
        <h2 class="text-xl font-semibold leading-tight text-gray-800">
            {{ __('Product List') }}
        </h2>
    </x-slot>

    @livewire('products-table')
</x-app-layout>

Enter fullscreen mode Exit fullscreen mode

Note: I will elaborate on this post later

Top comments (0)