Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Livewire Tables Laravel Package

timolake/livewire-tables

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require timolake/livewire-tables
    

    Publish the config (optional):

    php artisan vendor:publish --provider="Timolake\LivewireTables\LivewireTablesServiceProvider"
    
  2. Basic Usage Create a Livewire component that extends Timolake\LivewireTables\LivewireTable:

    use Timolake\LivewireTables\LivewireTable;
    
    class UserTable extends LivewireTable
    {
        public function configure(): void
        {
            $this->setPrimaryKey('id');
            $this->setSearch(['name', 'email']);
            $this->setColumns([
                'id',
                'name',
                'email',
            ]);
        }
    
        public function query(): \Illuminate\Database\Eloquent\Builder
        {
            return User::query();
        }
    }
    
  3. Render the Table

    <livewire:user-table />
    

    The package auto-generates pagination, search, and sorting UI.


First Use Case: Quick Data Grid

  • Need a sortable, searchable, paginated table in <10 minutes?
  • Use LivewireTable as a base class and define configure() + query().
  • No need to manually handle pagination/sorting—it’s built-in.

Implementation Patterns

1. Column Customization

  • Basic Columns: Define in setColumns().
    $this->setColumns(['id', 'name', 'email']);
    
  • Custom Views: Override getColumnContent():
    public function getNameContent($row): string
    {
        return "<strong>{$row->name}</strong>"; // HTML allowed
    }
    
  • Action Columns: Add buttons/links:
    $this->addActionColumn([
        'view' => fn($row) => view('livewire-tables::buttons.view', ['row' => $row]),
        'edit' => fn($row) => view('livewire-tables::buttons.edit', ['row' => $row]),
    ]);
    

2. Query Filtering

  • Search: Auto-applied via setSearch().
  • Custom Filters: Use addFilter():
    $this->addFilter('active', function ($query, $value) {
        return $query->where('is_active', $value);
    });
    
    Render filter UI in Blade:
    <livewire:user-table :filters="['active' => true]" />
    

3. Bulk Actions

  • Enable with setBulkActions():
    $this->setBulkActions([
        'delete' => fn($rows) => User::whereIn('id', $rows)->delete(),
    ]);
    
  • Render checkboxes and action buttons automatically.

4. Integration with Livewire Hooks

  • Use mountTable() for initialization logic:
    public function mountTable(): void
    {
        $this->setPerPage(20); // Override default
    }
    
  • Extend updatedSearch() or updatedSort() for custom logic.

5. Theming & Styling

  • Override default views by publishing assets:
    php artisan vendor:publish --tag=livewire-tables-views
    
  • Customize CSS/JS via public/css/livewire-tables.css.

Gotchas and Tips

Pitfalls

  1. Eager Loading

    • Forgetting to eager-load relationships causes N+1 queries.
    • Fix: Use with() in query():
      public function query(): Builder
      {
          return User::with('posts')->query();
      }
      
  2. Search Scope Conflicts

    • If setSearch() fields conflict with existing query scopes, override applySearch():
      protected function applySearch(): void
      {
          $this->query()->where('name', 'like', "%{$this->search}%");
      }
      
  3. Pagination Reset

    • Changing setPerPage() or filters does not reset pagination by default.
    • Force reset with:
      $this->resetPage();
      
  4. CSRF on Bulk Actions

    • Bulk actions (e.g., delete) may fail if CSRF token isn’t refreshed.
    • Add @csrf to Blade or use @this directive:
      <form wire:submit.prevent="deleteSelected" @this>
          @csrf
          <!-- ... -->
      </form>
      

Debugging Tips

  • Log Queries: Enable Laravel’s query logging:
    \DB::enableQueryLog();
    $this->query()->get(); // Inspect with dd(\DB::getQueryLog());
    
  • Check Wire Events: Use wire:debug to inspect Livewire events:
    @wire:debug
    <livewire:user-table />
    
  • Validate Inputs: Sanitize setSearch()/setSort() inputs to avoid SQL injection:
    $this->search = strtolower($this->search);
    

Extension Points

  1. Custom Table Classes

    • Extend LivewireTable for reusable table logic:
      class BaseTable extends LivewireTable
      {
          public function configure(): void
          {
              $this->setPerPage(15);
              $this->setSearch(['name']);
          }
      }
      
  2. Dynamic Columns

    • Fetch columns from a config file or API:
      $this->setColumns(config('table.columns'));
      
  3. Export Functionality

    • Integrate with spatie/laravel-excel:
      public function export()
      {
          return Excel::download(new UserExport, 'users.xlsx');
      }
      
    • Add a button in Blade:
      <button wire:click="export">Export</button>
      
  4. Server-Side Processing

    • For large datasets, override getData() to fetch only visible rows:
      public function getData(): array
      {
          return $this->query()
              ->skip($this->offset())
              ->take($this->perPage())
              ->get()
              ->toArray();
      }
      

Config Quirks

  • Default Per-Page: Set globally in config/livewire-tables.php:
    'per_page' => 10,
    
  • Disable Pagination: Set setPerPage(0) or override hasPagination():
    public function hasPagination(): bool { return false; }
    
  • Custom Sort Icons: Replace default icons by overriding getSortIcon():
    protected function getSortIcon(string $field): string
    {
        return $this->sort === $field ? '↑↓' : '→';
    }
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver