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

Laravel Livewire Datatable Only Arrays Laravel Package

dndarksan/laravel-livewire-datatable-only-arrays

Livewire v2 + Bootstrap 4 datatable component for arrays only. Install via Composer and generate tables with php artisan make:dt-table. Define headers, columns, and records arrays to enable sortable/searchable columns and per-cell classes.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require dndarksan/laravel-livewire-datatable-only-arrays
    

    Ensure Livewire v2 is already installed and configured in your Laravel project.

  2. Generate a Datatable Component:

    php artisan make:dt-table UserDatatable
    

    This creates a Livewire component (UserDatatable) in /app/Http/Livewire.

  3. Render the Component: Add @livewire('user-datatable') to your Blade view.


First Use Case

Create a simple datatable for a users table:

  1. Define Headers (encabezados()):
    public function encabezados(): array
    {
        return [
            [
                "name" => "ID",
                "campo" => "id",
                "sorteable" => true,
            ],
            [
                "name" => "Name",
                "campo" => "name",
                "searchable" => true,
            ],
        ];
    }
    
  2. Fetch Data (datos()):
    public function datos(): array
    {
        return User::all()->toArray();
    }
    
  3. Render in Blade:
    @livewire('user-datatable')
    

Implementation Patterns

Core Workflow

  1. Component Generation: Use make:dt-table to scaffold a new datatable component with pre-configured methods (encabezados, datos, etc.).

  2. Data Binding:

    • Headers: Define columns with metadata (name, campo, sorteable, searchable).
    • Data: Return an array of records (no Eloquent collections or objects). Use toArray() for Eloquent results.
      public function datos(): array
      {
          return User::query()
              ->when($this->search, fn($q) => $q->where('name', 'like', "%{$this->search}%"))
              ->get()
              ->toArray();
      }
      
  3. Sorting/Searching:

    • Enable sorting by setting "sorteable" => true and specifying "campo".
    • Enable search by setting "searchable" => true and handle the search logic in datos():
      public $search = '';
      
      public function updatingSearch()
      {
          $this->resetPage();
      }
      
  4. Pagination: Use Livewire’s built-in pagination:

    public function datos(): array
    {
        return User::paginate(10)->toArray();
    }
    

    Add pagination controls to your Blade view:

    {{ $this->withPagination() }}
    
  5. Styling: The package uses Bootstrap 4 by default. Customize via CSS or override the provided Blade template.


Integration Tips

  • API Integration: Fetch data from external APIs and transform responses into arrays:

    public function datos(): array
    {
        $response = Http::get('https://api.example.com/users');
        return $response->json();
    }
    
  • Dynamic Columns: Load headers dynamically based on user roles or permissions:

    public function encabezados(): array
    {
        if (auth()->user()->isAdmin) {
            return [...]; // Admin columns
        }
        return [...]; // Default columns
    }
    
  • Reusable Components: Extend the base component for shared functionality:

    class BaseDatatable extends DatatableOnlyArrays
    {
        public function getDefaultHeaders(): array { ... }
    }
    

Gotchas and Tips

Pitfalls

  1. Data Format:

    • MUST return arrays in datos(). Eloquent collections or objects will break the table.
    • Nested arrays (e.g., relationships) require manual flattening or custom rendering.
  2. Sorting/Searching:

    • Forgetting to include "campo" in headers disables sorting/searching.
    • Case-sensitive searches: Use strtolower() in search logic if needed:
      ->where('name', 'like', "%{$this->search}%")
      
  3. Pagination:

    • Livewire’s pagination conflicts with the package’s default pagination. Use paginate() instead of simplePaginate() for consistency.
  4. Blade Template Overrides: The package assumes a default Blade template. Override it by publishing assets:

    php artisan vendor:publish --tag=livewire-datatable-only-arrays
    

    Then modify /resources/views/vendor/livewire-datatable-only-arrays/....


Debugging

  1. Check Headers: Dump encabezados() to verify structure:

    dd($this->encabezados());
    
  2. Inspect Data: Log datos() output to ensure correct array format:

    \Log::debug('Datatable data:', $this->datos());
    
  3. Livewire Hooks: Use mount() or hydrate() to debug component initialization:

    public function mount()
    {
        \Log::info('Component mounted');
    }
    

Tips

  1. Performance:

    • Use cursor() for large datasets to avoid memory issues:
      public function datos(): array
      {
          return User::cursor()->get()->toArray();
      }
      
    • Lazy-load data with loadMore events.
  2. Localization: Customize labels (e.g., "No results") by overriding the Blade template.

  3. Extensions: Add custom actions (e.g., buttons) by extending the Blade template:

    <td>
        <button wire:click="edit({{ $item['id'] }})">Edit</button>
    </td>
    
  4. Testing: Test components with Livewire’s testing helpers:

    $this->livewire(UserDatatable::class)
        ->assertSee('User Table')
        ->assertDontSee('Error');
    
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.
directorytree/privacy-filter-classifier
directorytree/privacy-filter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity
testo/bridge-symfony
spatie/flare-daemon-runtime