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

Queue-based server-side exports for yajra/laravel-datatables using Livewire and OpenSpout. Adds an export-button component and WithExportQueue trait to DataTable classes, enabling scalable Excel/CSV-style exports via Laravel batch jobs.

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Install the package**:
   ```bash
   composer require yajra/laravel-datatables-export:"^13.0"
  1. Run migrations for queue batches:
    php artisan queue:batches-table
    php artisan migrate
    
  2. Publish optional assets/config:
    php artisan vendor:publish --tag=datatables-export --force
    

First Use Case

For a basic DataTable with export functionality:

  1. Extend your DataTable class:
    use Yajra\DataTables\WithExportQueue;
    
    class UsersDataTable extends DataTable
    {
        use WithExportQueue;
    
        // ... rest of your DataTable logic
    }
    
  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. DataTable Integration:

    • Use WithExportQueue trait in your DataTable class to enable queued exports.
    • Ensure your DataTable extends Yajra\DataTables\DataTable (or Yajra\DataTables\EloquentDataTable for Eloquent).
  2. Livewire Button Placement:

    • Place <livewire:export-button /> near your DataTable HTML element.
    • Pass the table ID (:table-id="$dataTable->getTableId()").
  3. Queue Processing:

    • Exports are processed asynchronously via Laravel queues.
    • Files are stored in storage/app/exports/ by default (configurable).

Common Patterns

  1. Dynamic Filename:

    <livewire:export-button
        :table-id="$dataTable->getTableId()"
        :filename="'users-' . now()->format('Y-m-d') . '.xlsx'"
    />
    
  2. Custom Export Types:

    <!-- CSV Export -->
    <livewire:export-button
        :table-id="$dataTable->getTableId()"
        type="csv"
        buttonName="Export as CSV"
    />
    
    <!-- Excel Export -->
    <livewire:export-button
        :table-id="$dataTable->getTableId()"
        type="xlsx"
        sheet-name="User Records"
    />
    
  3. Auto-Download:

    <livewire:export-button
        :table-id="$dataTable->getTableId()"
        auto-download="true"
    />
    
  4. Column Formatting:

    // In your DataTable class
    $this->addColumn('price', function ($row) {
        return '$' . number_format($row->price, 2);
    })->exportFormat('0.00');
    
  5. Date Handling:

    $this->addColumn('created_at', function ($row) {
        return $row->created_at->format('Y-m-d H:i:s');
    })->exportFormat('mm/dd/yyyy hh:mm:ss');
    

Advanced Patterns

  1. Custom Export Logic: Override getExportData() in your DataTable:

    protected function getExportData()
    {
        return $this->collection->map(function ($row) {
            return [
                'name' => $row->name,
                'custom_field' => $this->formatCustomField($row),
            ];
        });
    }
    
  2. Batch Processing: For large datasets, use chunking:

    use Yajra\DataTables\WithBatchProcessing;
    
    class LargeDataTable extends DataTable
    {
        use WithExportQueue, WithBatchProcessing;
    
        // ...
    }
    
  3. Post-Export Actions: Listen to export events in your EventServiceProvider:

    protected $listen = [
        'Yajra\DataTables\Events\ExportStarted' => [
            'App\Listeners\LogExportStart',
        ],
        'Yajra\DataTables\Events\ExportCompleted' => [
            'App\Listeners\NotifyExportComplete',
        ],
    ];
    

Gotchas and Tips

Common Pitfalls

  1. Queue Worker Required:

    • Exports will not work without a running queue worker (php artisan queue:work).
    • For production, use a process manager (Supervisor) to keep the worker running.
  2. File Storage Path:

    • Default path: storage/app/exports/.
    • Ensure the directory is writable and has sufficient disk space.
    • Customize in config/datatables-export.php:
      'export_path' => storage_path('app/exports/custom_path'),
      
  3. Livewire Version:

    • Requires Livewire 4.x (check composer.json).
    • If using Livewire 3, downgrade to yajra/laravel-datatables-export:^12.3.
  4. PHP Version:

    • PHP 8.3+ required (OpenSpout 5.x dependency).
    • For PHP 8.2, use yajra/laravel-datatables-export:^12.3.
  5. Empty Values:

    • Empty values may be converted to null in exports. Use ->exportFormat('@') to force text:
      Column::make('nullable_field')->exportFormat('@');
      
  6. Date Formats:

    • Ensure date formats match OpenSpout’s supported formats (see config/datatables-export.php).
    • Common issue: Y-m-d may not work; use mm/dd/yyyy or NumberFormat::FORMAT_DATE_YYYYMMDD.
  7. Large Files:

    • Exports >100MB may hit memory limits. Use batch processing:
      use WithBatchProcessing;
      
    • Monitor queue jobs with php artisan queue:failed and retry as needed.
  8. Button Visibility:

    • The export button relies on the DataTable’s getTableId(). Ensure this is unique per table instance.

Debugging Tips

  1. Queue Logs:

    • Check storage/logs/laravel.log for export job failures.
    • Tail logs in real-time:
      tail -f storage/logs/laravel.log
      
  2. Export Job Inspection:

    • List pending jobs:
      php artisan queue:list
      
    • View job details:
      php artisan queue:work --once --verbose
      
  3. File Permissions:

    • Verify storage permissions:
      chmod -R 755 storage/app/exports
      
  4. Configuration Overrides:

    • Publish config to customize:
      php artisan vendor:publish --tag=datatables-export-config
      
    • Key settings:
      'export_path' => 'custom/path',
      'disk' => 's3', // For cloud storage
      'auto_download' => true,
      

Extension Points

  1. Custom Export Formats: Extend Yajra\DataTables\Formatters\NumberFormat for new formats:

    class CustomNumberFormat extends NumberFormat
    {
        const FORMAT_CUSTOM = 'custom_format';
    
        public static function getFormat(self::FORMAT_CUSTOM)
        {
            return ['type' => self::TYPE_NUMBER, 'formatCode' => '#,##0.00;(#,##0.00)'];
        }
    }
    
  2. Pre/Post Export Hooks: Use events to modify export behavior:

    // app/Providers/EventServiceProvider.php
    protected $listen = [
        'Yajra\DataTables\Events\ExportStarted' => [
            'App\Listeners\ModifyExportData',
        ],
    ];
    
  3. Storage Backends: Customize storage using Laravel’s filesystem:

    // config/datatables-export.php
    'disk' => 's3',
    'export_path' => 'exports',
    
  4. Livewire Component Extensions: Override ExportButton to add custom logic:

    namespace App\Livewire;
    
    use Yajra\DataTables\Livewire\ExportButton as BaseExportButton;
    
    class CustomExportButton extends BaseExportButton
    {
        public function mount($tableId, $type = 'xlsx', $filename = null)
        {
            $this->filename = $filename ?? 'custom_' . $this->tableId . '.' . $type;
            // Custom logic here
        }
    }
    
  5. Queue Chunking: For very large exports, implement chunked processing:

    use Yajra\DataTables\WithBatchProcessing;
    
    class LargeExportDataTable extends DataTable
    {
        use WithExportQueue, WithBatchProcessing;
    
        public function __construct()
        {
            $this->batchSize = 1000; // Process 10
    
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.
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
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope
anil/file-picker
broqit/fields-ai