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

Tctable Laravel Package

voilab/tctable

Laravel package for building sortable, filterable, paginated tables from Eloquent data. Define columns and actions, render via views, and handle server-side searching and ordering. Useful for admin panels and data listings with minimal boilerplate.

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Steps
1. **Installation**
   ```bash
   composer require voilab/tctable tecnickcom/tcpdf

Register the service provider in config/app.php:

'providers' => [
    Voilab\TcTable\TcTableServiceProvider::class,
],
  1. First Use Case: Quick PDF Table

    use Voilab\TcTable\Facades\TcTable;
    
    $data = [
        ['id' => 1, 'name' => 'John Doe', 'email' => 'john@example.com'],
        ['id' => 2, 'name' => 'Jane Smith', 'email' => 'jane@example.com'],
    ];
    
    $pdf = TcTable::make()
        ->setData($data)
        ->setHeaders(['ID', 'Name', 'Email'])
        ->renderAndDownload('users.pdf');
    
  2. Where to Look First

    • Facade: TcTable for quick usage.
    • Configuration: config/tctable.php for defaults.
    • Documentation: Check vendor/voilab/tctable/README.md for advanced options.

Implementation Patterns

Core Usage Patterns

  1. Data-Driven Tables

    // Eloquent Collection
    $table = TcTable::make()
        ->setData(User::all()->toArray())
        ->setHeaders(['ID', 'Name', 'Email']);
    
    // Raw Query
    $table->setData(DB::table('users')->get()->toArray());
    
  2. Dynamic Styling

    $table->setStyle([
        'header' => ['font' => 'helvetica', 'size' => 10, 'bold' => true, 'bgcolor' => [200, 200, 200]],
        'cell'   => ['padding' => 3, 'border' => 0.3, 'align' => 'C'],
    ]);
    
  3. Pagination Control

    $table->setPageBreakOptions([
        'maxRowsPerPage' => 25, // Force page break every 25 rows
        'breakOn' => ['header', 'footer'], // Preserve headers/footers
        'mode' => 'full', // Break entire table if needed
    ]);
    
  4. Memory-Efficient Chunking

    $table->setChunkSize(1000)
         ->setData(User::query()->cursor()); // Stream data
    
  5. Blade Integration

    // Controller
    return view('report', [
        'table' => TcTable::make()->setData($data)->setHeaders($headers),
    ]);
    
    // Blade
    {!! $table->render() !!}
    
  6. Custom Cell Logic

    $table->setCellCallback(function ($row, $column) {
        if ($column === 'status') {
            return $row['active'] ? '<span style="color:green">Active</span>' : '<span style="color:red">Inactive</span>';
        }
        return $row[$column];
    });
    
  7. Async Generation with Queues

    // Job
    class GeneratePdfJob implements ShouldQueue
    {
        public function handle()
        {
            $table = TcTable::make()
                ->setData($this->data)
                ->setHeaders($this->headers)
                ->renderAndStore('path/to/file.pdf');
        }
    }
    
    // Dispatch
    GeneratePdfJob::dispatch($data, $headers)->onQueue('pdfs');
    
  8. Storage Integration

    use Illuminate\Support\Facades\Storage;
    
    $table->renderAndStore('reports/users.pdf', 'public');
    $url = Storage::url('reports/users.pdf');
    

Gotchas and Tips

Common Pitfalls

  1. Memory Limits

    • Issue: Large datasets may hit PHP memory limits.
    • Fix: Use chunking with cursor() or chunk():
      $table->setChunkSize(500)->setData(User::query()->cursor());
      
    • Debug: Check memory_get_usage() in your job.
  2. TCPDF Configuration Conflicts

    • Issue: Default TCPDF settings may override your styles.
    • Fix: Configure TCPDF in config/tctable.php:
      'tcpdf' => [
          'default_font' => 'dejavusans',
          'default_font_size' => 8,
          'margin' => [15, 15, 15, 15],
      ],
      
  3. Page Break Anomalies

    • Issue: Headers/footers may misalign after breaks.
    • Fix: Explicitly set page break options:
      $table->setPageBreakOptions([
          'breakOn' => ['header', 'footer'],
          'mode' => 'full',
      ]);
      
  4. Data Type Errors

    • Issue: Non-array data breaks rendering.
    • Fix: Validate input:
      if (!is_array($data)) {
          $data = $data->toArray(); // For Laravel Collections
      }
      
  5. Styling Not Applying

    • Issue: Styles may be ignored due to TCPDF defaults.
    • Fix: Use explicit style overrides:
      $table->setStyle([
          'header' => ['font' => 'helvetica', 'size' => 10, 'bold' => true],
          'cell'   => ['padding' => 4, 'border' => 0.5, 'align' => 'L'],
      ]);
      
  6. Font Loading Failures

    • Issue: Custom fonts may not load.
    • Fix: Ensure TCPDF fonts are added:
      $pdf = $table->getPdf();
      $pdf->AddFont('dejavusans', '', 'DejaVuSans.php');
      

Debugging Tips

  1. Enable TCPDF Debugging

    $pdf = $table->getPdf();
    $pdf->SetPrintHeader(true);
    $pdf->SetPrintFooter(true);
    $pdf->SetDebug(true);
    
  2. Log Table Data

    \Log::debug('Table Data:', ['data' => $table->getData()]);
    
  3. Check TCPDF Errors

    try {
        $table->render();
    } catch (\Exception $e) {
        \Log::error('TCPDF Error: ' . $e->getMessage());
        // Fallback to alternative PDF generation
    }
    

Performance Optimization

  1. Lazy Loading

    $table->setLazyLoad(true)->setData(User::query()->cursor());
    
  2. Cache Generated PDFs

    $pdfPath = cache()->remember("pdf_{$userId}", now()->addHours(1), function () use ($table) {
        return $table->renderAndStore("user_{$userId}.pdf");
    });
    
  3. Queue Batch Processing

    foreach ($userIds as $id) {
        GeneratePdfJob::dispatch($id)->onQueue('pdfs');
    }
    

Extension Points

  1. Custom TCPDF Instance

    $pdf = new \TCPDF();
    $pdf->SetCreator('Your App');
    $table = new \Voilab\TcTable\TcTable($pdf);
    
  2. Override Rendering Logic

    $table->setRenderer(function ($pdf, $data, $headers) {
        // Custom rendering logic
        $pdf->AddPage();
        $pdf->writeHTML($this->generateCustomHtml($data, $headers));
    });
    
  3. Add Custom Headers/Footers

    $table->setHeaderCallback(function ($pdf) {
        $pdf->SetFont('helvetica', 'B', 12);
        $pdf->Cell(0, 10, 'Custom Header', 0, false, 'C');
    });
    
  4. Integrate with Laravel Events

    event(new PdfGenerated($pdfPath, $userId));
    

Configuration Quirks

  1. Default Values

    • Check config/tctable.php for:
      • Default font, size, and colors.
      • Page break settings.
      • Memory limits.
  2. Environment-Specific Settings

    if (app()->environment('production')) {
        $table->setChunkSize(2000); // Larger chunks in production
    }
    
  3. TCPDF Version Pinning

    • Lock TCPDF version in composer.json:
      "require": {
          "tecnickcom/tcpdf": "6.5.2"
      }
      

Laravel-Specific Tips

  1. Service Provider Binding
    $this->app->bind(TcTable::class, function ($app) {
        $
    
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky