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

amirami/livewire-datatables

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require amirami/livewire-datatables
    php artisan vendor:publish --provider="Amirami\LivewireDataTables\LivewireDataTablesServiceProvider" --tag="livewire-datatables-config"
    

    Publish the config to customize default settings (e.g., datatables.php).

  2. Basic Setup:

    • Extend Amirami\LivewireDataTables\Traits\LivewireDataTable in your Livewire component.
    • Define a getData() method to return a query builder instance or collection:
      use Amirami\LivewireDataTables\Traits\LivewireDataTable;
      
      class UserDataTable extends Component
      {
          use LivewireDataTable;
      
          public function getData()
          {
              return User::query();
          }
      }
      
    • Include the component in your Blade view:
      <livewire:user-data-table />
      
  3. First Use Case: Display a paginated table with search and sorting:

    // In your component
    public function configure()
    {
        return $this->setPrimaryKey('id')
                    ->setSearchColumn('name')
                    ->setPerPage(10);
    }
    

Implementation Patterns

Core Workflows

  1. Query Building:

    • Use getData() to return a query builder or collection. The package handles pagination, search, and sorting automatically.
    • Customize queries with getQuery():
      public function getQuery()
      {
          return $this->getData()->where('active', true);
      }
      
  2. Column Configuration:

    • Define columns in getColumns():
      public function getColumns()
      {
          return [
              'id' => 'ID',
              'name' => 'Name',
              'email' => 'Email',
          ];
      }
      
    • Customize column rendering with getColumnFields():
      public function getColumnFields()
      {
          return [
              'name' => 'name',
              'email' => function ($value) {
                  return Str::limit($value, 20);
              },
          ];
      }
      
  3. Actions and Buttons:

    • Add action buttons via getActions():
      public function getActions()
      {
          return [
              'edit' => 'Edit',
              'delete' => 'Delete',
          ];
      }
      
    • Define action logic in getActionButtons():
      public function getActionButtons()
      {
          return [
              'edit' => function ($row) {
                  return '<a href="/users/' . $row->id . '/edit">Edit</a>';
              },
              'delete' => function ($row) {
                  return '<button wire:click="delete(' . $row->id . ')" class="btn btn-danger">Delete</button>';
              },
          ];
      }
      
  4. Modular Components:

    • Break down complex tables into smaller components (e.g., UserDataTable, OrderDataTable) by reusing the trait.
  5. Integration with Livewire:

    • Leverage Livewire's reactivity for real-time updates:
      public function delete($id)
      {
          User::find($id)->delete();
          $this->dispatchBrowserEvent('table-updated');
      }
      

Integration Tips

  1. Styling:

    • Use Tailwind, Bootstrap, or custom CSS. The package is framework-agnostic for styling.
    • Example with Bootstrap:
      <div class="table-responsive">
          <livewire:user-data-table />
      </div>
      
  2. API Integration:

    • Fetch data from external APIs by returning a collection in getData():
      public function getData()
      {
          return collect(Http::get('https://api.example.com/users')->json());
      }
      
  3. Relationships:

    • Eager load relationships in getData():
      public function getData()
      {
          return User::with('roles')->query();
      }
      
    • Display nested data in columns:
      public function getColumnFields()
      {
          return [
              'role' => function ($value) {
                  return $value->roles->first()->name ?? 'None';
              },
          ];
      }
      
  4. Custom Views:

    • Override the default table view by publishing assets:
      php artisan vendor:publish --provider="Amirami\LivewireDataTables\LivewireDataTablesServiceProvider" --tag="livewire-datatables-views"
      
    • Modify resources/views/vendor/livewire-datatables/table.blade.php.
  5. Localization:

    • Customize labels (e.g., "No results found") in the config file:
      'labels' => [
          'no_results' => 'No records found.',
      ],
      

Gotchas and Tips

Pitfalls

  1. Query Caching:

    • Avoid caching the query result in getData() if using real-time updates. The package re-executes the query on each request.
    • Example of wrong approach:
      private $users;
      public function getData() {
          if (!$this->users) {
              $this->users = User::all();
          }
          return $this->users;
      }
      
  2. Primary Key Conflicts:

    • Ensure setPrimaryKey() matches the actual primary key of your model. Conflicts may cause silent failures in row selection.
  3. Column Mismatches:

    • If getColumns() and getColumnFields() have mismatched keys, the table may render incorrectly or throw errors.
    • Validate keys in getColumnFields() against getColumns().
  4. Livewire Hooks:

    • Overriding mount() or hydrate() may interfere with the package's initialization. Avoid modifying these unless necessary.
  5. Pagination Conflicts:

    • If using custom pagination logic (e.g., cursor-based), disable the package's pagination:
      public function configure()
      {
          return $this->disablePagination();
      }
      

Debugging

  1. Query Logs:

    • Enable Laravel's query logging to inspect generated SQL:
      DB::enableQueryLog();
      // After table renders
      dd(DB::getQueryLog());
      
  2. Wire:Debug:

    • Use Livewire's debug mode to inspect component properties:
      @livewireScripts
      <script>
          window.addEventListener('livewire:init', () => {
              Livewire.debug = true;
          });
      </script>
      
  3. Event Listeners:

    • Listen for livewire-data-table-updated events to debug real-time changes:
      window.addEventListener('livewire-data-table-updated', (event) => {
          console.log('Table updated:', event.detail);
      });
      

Tips

  1. Performance:

    • Use select() to limit columns in getData():
      public function getData()
      {
          return User::query()->select('id', 'name', 'email');
      }
      
    • Add indexes to frequently filtered/sorted columns.
  2. Conditional Logic:

    • Dynamically adjust columns/actions based on user roles:
      public function getColumns()
      {
          $columns = ['id', 'name'];
          if (auth()->user()->isAdmin) {
              $columns[] = 'email';
          }
          return $columns;
      }
      
  3. Reusability:

    • Create a base component for shared configurations:
      class BaseDataTable extends Component
      {
          use LivewireDataTable;
      
          public function configure()
          {
              return $this->setPerPage(20)->setSearchColumn('name');
          }
      }
      
  4. Testing:

    • Test components with Livewire::test():
      public function test_table_renders()
      {
          Livewire::test(UserDataTable::class)
              ->assertSee('User Table')
              ->assertStatus(200);
      }
      
  5. Extensions:

    • Extend functionality by creating custom traits or middleware:
      trait ExportableDataTable
      {
          public function export()
          {
              return Excel::download(new UserExport($this->getData()), 'users.xlsx');
          }
      }
      
    • Attach to your component:
      use ExportableDataTable;
      
      class UserDataTable extends Component
      {
          use LivewireDataTable, ExportableDataTable;
      }
      
  6. Config Overrides:

    • Override default settings globally in config/datatables.php:
      'default_per_page' => 50,
      'enable_search' => false,
      
  7. Hidden Columns:

    • Hide columns from the UI but keep them in the query:
      public function getColumns()
      {
          return [
              'id' => 'ID',
              'hidden_column' => 'Hidden',
          ];
      }
      
      public function getColumn
      
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.
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
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle