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 Datatables Laravel Package

arm092/livewire-datatables

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require arm092/livewire-datatables
    

    Publish assets (optional but recommended for customization):

    php artisan vendor:publish --provider="Arm092\LivewireDatatables\LivewireDatatablesServiceProvider"
    
  2. First Component: Create a Livewire component targeting a model (e.g., User):

    php artisan make:livewire Admin/UserTable
    

    Update the component class (app/Http/Livewire/Admin/UserTable.php):

    use Arm092\LivewireDatatables\DataTableComponent;
    use App\Models\User;
    
    class UserTable extends DataTableComponent
    {
        public function configure(): void
        {
            $this->setPrimaryKey('id');
            $this->setModel(User::class);
            $this->setSearch(true);
            $this->setPerPage(10);
        }
    
        public function columns(): array
        {
            return [
                'name' => 'Name',
                'email' => 'Email',
                'created_at' => 'Created At',
            ];
        }
    }
    
  3. Blade Integration: Render the table in your view (resources/views/livewire/admin/user-table.blade.php):

    <div>
        {!! $this->table(['showCheckboxes' => true]) !!}
    </div>
    
  4. Run Migrations/Seeders: Ensure your database is populated before testing.


First Use Case: Basic CRUD Table

  • Goal: Display a paginated, searchable list of users with sorting.
  • Steps:
    1. Create the component as above.
    2. Add a create button linking to a form (e.g., route('users.create')).
    3. Use Livewire’s $emit to refresh the table post-create:
      // In your create controller
      return redirect()->route('users.index')->with('success', 'User created!');
      
    4. Add a flash message handler in the component:
      public function mount(): void
      {
          $this->emit('alert', 'success', 'User created!');
      }
      

Implementation Patterns

Core Workflows

1. Data Binding

  • Model Binding: Use setModel() to bind to Eloquent models or query builders:
    $this->setModel(User::query()->where('active', true));
    
  • Custom Data Sources: Override getData() for non-model data (e.g., API responses):
    public function getData(): array
    {
        return $this->apiClient->fetchUsers();
    }
    

2. Column Configuration

  • Basic Columns:
    public function columns(): array
    {
        return [
            'id' => 'ID',
            'name' => 'Name',
            'email' => fn(User $user) => Str::of($user->email)->lower(),
        ];
    }
    
  • Computed Columns: Add logic via closures:
    'full_name' => fn(User $user) => "{$user->first_name} {$user->last_name}",
    
  • Action Columns: Use Html::button() or Html::link():
    'actions' => fn(User $user) => Html::link(
        route('users.edit', $user),
        'Edit',
        ['class' => 'text-blue-500']
    ),
    

3. Filtering

  • Simple Filters: Enable search globally:
    $this->setSearch(true);
    
    Or add custom filters:
    public function filters(): array
    {
        return [
            'role' => ['x' => 'Admin', 'y' => 'User'],
            'active' => ['x' => true, 'y' => false],
        ];
    }
    
  • Complex Filters: Use complexQueryBuilder for multi-condition filters:
    public function complexQueryBuilder(): array
    {
        return [
            'name' => 'Name',
            'email' => 'Email',
            'role' => 'Role',
        ];
    }
    

4. Mass Actions

  • Bulk Operations: Enable checkboxes and define actions:
    $this->setShowCheckboxes(true);
    $this->setActions([
        'delete' => 'Delete',
        'export' => 'Export',
    ]);
    
    Handle actions in the component:
    public function deleteSelected(): void
    {
        $this->selected()->each->delete();
        $this->emit('alert', 'success', 'Items deleted!');
    }
    

5. Column Groups

  • Grouping: Organize columns into collapsible sections:
    public function columns(): array
    {
        return [
            'group:user_info' => [
                'name' => 'Name',
                'email' => 'Email',
            ],
            'group:metadata' => [
                'created_at' => 'Created At',
                'updated_at' => 'Updated At',
            ],
        ];
    }
    

Integration Tips

Livewire Events

  • Refresh Data: Use $this->emit('refresh') or $this->refresh() after external changes (e.g., soft deletes).
  • Custom Events: Trigger Alpine.js events for frontend interactions:
    $this->emit('show-modal', ['id' => $user->id]);
    

Tailwind Styling

  • Override Defaults: Publish the config and modify resources/views/vendor/livewire-datatables/table.blade.php:
    <table class="min-w-full divide-y divide-gray-200 {{ $classes ?? '' }}">
    
  • Dynamic Classes: Use Alpine.js to toggle classes:
    x-data="{ expanded: false }"
    @click="expanded = !expanded"
    :class="{ 'bg-gray-50': expanded }"
    

API Integration

  • Remote Data: Fetch data via AJAX in getData():
    public function getData(): array
    {
        $response = Http::get('https://api.example.com/users');
        return $response->json();
    }
    

Testing

  • Unit Tests: Mock the data source:
    $component = new UserTable();
    $component->setData(collect([new User()]));
    $component->render();
    
  • Feature Tests: Test filtering/sorting:
    $this->livewire(UserTable::class)
         ->setSearch('test')
         ->assertSee('test');
    

Gotchas and Tips

Pitfalls

  1. Performance with Large Datasets:

    • Issue: Slow rendering with >10k rows.
    • Fix: Use setPerPage(50) and implement server-side processing (override getData() to paginate API responses).
  2. Filter Persistence:

    • Issue: Filters reset on page reload.
    • Fix: Store filters in session or URL:
      public function mount(): void
      {
          $this->filters = session('datatable_filters', []);
      }
      
  3. Column Sorting Conflicts:

    • Issue: Sorting fails on computed columns.
    • Fix: Ensure computed columns return sortable values:
      'full_name' => [
          'label' => 'Full Name',
          'sortable' => true,
          'accessor' => fn(User $user) => "{$user->first_name} {$user->last_name}",
      ],
      
  4. Tailwind Conflicts:

    • Issue: Styling breaks due to Tailwind version mismatches.
    • Fix: Extend the published config to override utilities:
      'table' => [
          'classes' => 'w-full',
          'thead' => 'bg-gray-50',
      ],
      
  5. Mass Action Race Conditions:

    • Issue: Selected items change during bulk operations.
    • Fix: Clone the selection array:
      $ids = clone $this->selected()->pluck('id');
      

Debugging Tips

  1. Log Queries: Enable Laravel query logging in AppServiceProvider:

    DB::enableQueryLog();
    

    Dump queries in getData():

    dd(DB::getQueryLog());
    
  2. Inspect Component State: Use dd($this->getData()) or dd($this->filters) to debug data binding.

  3. Alpine.js Console: Check browser console for Alpine errors (e.g., missing x-data bindings).

  4. Livewire Hooks: Override updated() to log changes:

    public function updated($property): void
    {
        \Log::debug("Property '$property' updated to: " . $this->$property
    
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware