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

Laravel DataTables export plugin for server-side exporting via queued jobs, OpenSpout, and Livewire. Adds an export button component and DataTable trait (WithExportQueue) to generate Excel/CSV exports for jQuery DataTables 2.x on Laravel 13.

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Install the package** in your Laravel 13.x project:
   ```bash
   composer require yajra/laravel-datatables-export:"^13.0"
  1. Run migrations for the export queue:
    php artisan queue:batches-table
    php artisan migrate
    
  2. Publish config (optional, for customization):
    php artisan vendor:publish --tag=datatables-export --force
    

First Use Case

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

Implementation Patterns

Core Workflow

  1. Queue-Based Export:

    • Clicking the export button triggers a queued job (non-blocking).
    • The job processes the export asynchronously using OpenSpout (CSV/XLSX).
    • Files are stored temporarily in storage/app/export/.
  2. Livewire Integration:

    • The <livewire:export-button> component handles UI state (e.g., loading/spinner).
    • Supports dynamic props like filename, type (csv/xlsx), and auto-download.
  3. DataTable Customization:

    • Use Column::make() to define export formats:
      Column::make('price')->exportFormat('0.00'),
      Column::make('date')->exportFormat('mm/dd/yyyy'),
      

Common Patterns

  • Dynamic Filenames:
    <livewire:export-button
        :table-id="$dataTable->getTableId()"
        :filename="'users_' . now()->format('Y-m-d') . '.xlsx'"
    />
    
  • Conditional Export Buttons:
    @if(auth()->user()->can('export-users'))
        <livewire:export-button :table-id="$dataTable->getTableId()" />
    @endif
    
  • Sheet Naming: Override sheetName() in your DataTable:
    protected function sheetName(): string
    {
        return "Active Users - " . now()->format('Y');
    }
    

Integration Tips

  1. Queue Configuration:

    • Use queue:work --daemon for production.
    • Monitor jobs with php artisan queue:failed and retry with php artisan queue:retry.
  2. File Cleanup:

    • Schedule purging old exports in app/Console/Kernel.php:
      $schedule->command('datatables:purge-export')->weekly();
      
  3. Custom Export Logic:

    • Extend the ExportQueue class to add pre/post-processing:
      use Yajra\DataTables\ExportQueue;
      
      class CustomExportQueue extends ExportQueue
      {
          protected function beforeExport()
          {
              // Add custom logic (e.g., headers, footers)
          }
      }
      

Gotchas and Tips

Pitfalls

  1. Queue Worker Required:

    • Exports will not work without a running queue worker (php artisan queue:work).
    • Use QUEUE_CONNECTION=database in .env for testing (but avoid in production).
  2. File Storage Paths:

    • Exports are saved to storage/app/export/. Ensure this directory is writable.
    • For S3, configure FILESYSTEM_DISK=s3 in .env and verify the tmp_path setting in datatables-export.php.
  3. Livewire Version Mismatch:

    • The package requires Livewire 4.x. Conflicts may arise with older versions.
  4. Date Format Issues:

    • Invalid date formats (e.g., dd/mm/yyyy not in date_formats config) will default to raw values.
    • Use NumberFormat constants for consistency:
      Column::make('created_at')->exportFormat(NumberFormat::FORMAT_DATE_DATETIME),
      
  5. Empty Values:

    • Empty strings or null values may be replaced with 0 or null in exports. Use exportFormat('@') to force text:
      Column::make('notes')->exportFormat('@'),
      

Debugging Tips

  1. Check Queue Jobs:

    • Inspect failed jobs with:
      php artisan queue:failed
      
    • Tail logs for errors:
      tail -f storage/logs/laravel.log
      
  2. Verify Export Paths:

    • Temporarily log the export path in your DataTable’s export() method:
      public function export()
      {
          \Log::info('Export path:', [$this->getExportPath()]);
          return parent::export();
      }
      
  3. Test with Small Datasets:

    • Use ->limit(10) in your DataTable query to debug formatting issues without overwhelming the queue.

Extension Points

  1. Custom Export Formats:

    • Extend Yajra\DataTables\Formatters\NumberFormat to add new formats:
      class CustomNumberFormat extends NumberFormat
      {
          const FORMAT_CUSTOM = 'custom_format';
          // ...
      }
      
  2. Override Export Logic:

    • Subclass Yajra\DataTables\ExportQueue to modify the export process:
      class CustomExportQueue extends ExportQueue
      {
          protected function getWriter()
          {
              // Customize writer logic (e.g., add encryption)
              return parent::getWriter();
          }
      }
      
  3. Add New Export Types:

    • Support PDF exports by extending the ExportQueue and integrating a library like barryvdh/laravel-dompdf.

Configuration Quirks

  1. OpenSpout vs. PHPSpreadsheet:

    • The package defaults to OpenSpout (faster for large datasets). To force PHPSpreadsheet, set:
      'export' => [
          'driver' => 'phpspreadsheet',
      ],
      
    • Requires phpoffice/phpspreadsheet (^1.25).
  2. Date Format Overrides:

    • Customize date_formats in config/datatables-export.php to support your preferred formats:
      'date_formats' => [
          'your-custom-format',
          // ...
      ],
      
  3. Auto-Download Behavior:

    • When auto-download="true", the browser triggers a download immediately after the queue job completes.
    • Ensure your queue worker processes jobs quickly to avoid timeouts.

Performance Tips

  1. Batch Processing:

    • For large datasets (>10,000 rows), use chunking in your DataTable query:
      $this->query->chunk(1000, function ($rows) {
          // Process rows in batches
      });
      
  2. Queue Priorities:

    • Set job priority in the export button:
      <livewire:export-button :table-id="$dataTable->getTableId()" priority="high" />
      
  3. Memory Limits:

    • Increase PHP memory limit in .env for large exports:
      MEMORY_LIMIT=4G
      

---
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport