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

yajra/laravel-datatables-export

Server-side export plugin for yajra/laravel-datatables using queues, Livewire, and OpenSpout. Adds an export-button component and queued batch jobs to generate spreadsheet exports from DataTable classes on Laravel 13 (PHP 8.3+).

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the package:
    composer require yajra/laravel-datatables-export:"^13.0"
    
  2. Run migrations and batch table setup:
    php artisan queue:batches-table
    php artisan migrate
    
  3. Publish optional assets/config:
    php artisan vendor:publish --tag=datatables-export --force
    

First Use Case

  • Add the export button to your Livewire view:
    <livewire:export-button :table-id="$dataTable->getTableId()" />
    
  • Extend your DataTable class with WithExportQueue:
    use Yajra\DataTables\WithExportQueue;
    
    class UsersDataTable extends DataTable
    {
        use WithExportQueue;
    
        // Your DataTable methods...
    }
    
  • Start queue worker (in a separate terminal):
    php artisan queue:work
    

Implementation Patterns

Core Workflow

  1. Queue-Based Export:

    • Exports are processed asynchronously via Laravel queues, preventing UI lag for large datasets.
    • Use WithExportQueue trait to enable queued exports in your DataTable class.
  2. Livewire Integration:

    • The <livewire:export-button> component handles UI interaction and job dispatching.
    • Supports dynamic table IDs, filenames, and export types (CSV/XLSX).
  3. Column Formatting:

    • Define export formats per column:
      Column::make('price')->exportFormat('0.00');
      Column::make('date')->exportFormat('mm/dd/yyyy');
      
    • Auto-detects numeric/date fields with customizable formats (see config/datatables-export.php).
  4. Dynamic Filenames:

    • Pass a dynamic filename via Livewire:
      <livewire:export-button :table-id="$dataTable->getTableId()" :filename="$customFilename" />
      

Advanced Patterns

  • Custom Sheet Names: Override sheetName() in your DataTable class:

    protected function sheetName(): string
    {
        return "Custom Report - " . now()->format('Y-m');
    }
    
  • Auto-Download: Force immediate download:

    <livewire:export-button :table-id="$dataTable->getTableId()" auto-download="true" />
    
  • QueryBuilder Support: Works seamlessly with Eloquent or QueryBuilder queries.

  • Batch Processing: Configure queue connection in config/datatables-export.php (v13.2.0+):

    'queue_connection' => env('QUEUE_CONNECTION', 'database'),
    

Integration Tips

  • Pair with yajra/laravel-datatables-buttons: Required dependency for full functionality (e.g., buttons integration).
  • Livewire 4+ Compatibility: Uses Livewire’s job system for async exports.
  • Storage Handling: Exported files are stored in storage/app/exports/ by default. Clean up with:
    php artisan datatables:purge-export
    
    Schedule this in app/Console/Kernel.php:
    $schedule->command('datatables:purge-export')->weekly();
    

Gotchas and Tips

Common Pitfalls

  1. Queue Worker Required:

    • Exports won’t work without a running queue worker (php artisan queue:work).
    • For production, use a supervised process (e.g., Supervisor).
  2. Missing yajra/laravel-datatables-buttons:

    • Install it explicitly:
      composer require yajra/laravel-datatables-buttons:"^13.0"
      
  3. PHP Version Mismatch:

    • Requires PHP 8.3+ (OpenSpout v5+). Downgrade to v12.x for PHP 8.1/8.2.
  4. Livewire Component Not Found:

    • Ensure the Livewire component is registered in resources/views/vendor/livewire/components/export-button.blade.php.
    • Publish assets if missing:
      php artisan vendor:publish --tag=datatables-export --force
      
  5. Empty Values in Exports:

    • Empty values may be replaced with null. Use exportFormat('@') to force text:
      Column::make('nullable_field')->exportFormat('@');
      

Debugging Tips

  • Check Queue Jobs: Monitor jobs in .env database or Horizon (if installed):

    php artisan queue:list
    php artisan queue:work --once
    
  • Log Export Paths: Temporarily log file paths in Yajra\DataTables\Export\ExportController to verify storage.

  • Validate Config: Ensure config/datatables-export.php matches your Laravel version (e.g., queue_connection).

Extension Points

  1. Custom Export Logic: Override getExportData() in your DataTable class to modify exported data:

    protected function getExportData()
    {
        return $this->query->with(['relationship'])->get();
    }
    
  2. Add New Export Types: Extend Yajra\DataTables\Export\Export to support PDF/JSON exports.

  3. Modify Storage: Change the export directory in config/datatables-export.php:

    'export_path' => storage_path('app/custom-exports'),
    
  4. Livewire Event Hooks: Listen to export events (e.g., export.started) via Livewire’s $dispatch:

    protected $listen = ['export.started' => 'handleExportStart'];
    

Performance Considerations

  • Large Datasets: Use chunk() in your query to avoid memory issues:
    $this->query->chunk(1000, function ($rows) {
        // Process rows...
    });
    
  • Queue Throttling: Configure QUEUE_WORKER_TIMEOUT in .env to prevent long-running jobs.

Configuration Quirks

  • OpenSpout vs. PHPSpreadsheet: The package defaults to OpenSpout (lightweight). For PHPSpreadsheet, install:

    composer require phpoffice/phpspreadsheet
    

    Then set in config:

    'spreadsheet_driver' => 'PhpSpreadsheet',
    
  • Date Format Auto-Detection: Ensure date columns use valid formats from config/datatables-export.php. Add custom formats as needed.

  • Livewire 3 vs. 4: If using Livewire 3, pin to v12.x of this package to avoid compatibility issues.


```markdown
### Pro Tips
- **Dynamic Filenames with Logic**:
  Use Livewire properties to generate filenames dynamically:
  ```html
  <livewire:export-button
      :table-id="$dataTable->getTableId()"
      :filename="'report-' . now()->format('Y-m-d') . '.xlsx'"
  />
  • Conditional Export Buttons: Show/hide buttons based on user roles:

    @can('export-data')
        <livewire:export-button :table-id="$dataTable->getTableId()" />
    @endcan
    
  • Test Exports Locally: Use php artisan queue:work --once to manually trigger exports during development.

  • Monitor Export Status: Track job progress via Livewire’s $this->dispatch() or a separate status table.

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.
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
ecotone/kafka
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata