PHP code example of samuelterra22 / laravel-report-generator

1. Go to this page and download the library: Download samuelterra22/laravel-report-generator library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

samuelterra22 / laravel-report-generator example snippets


use SamuelTerra22\ReportGenerator\Facades\PdfReport;

public function usersReport()
{
    $query = User::select(['name', 'email', 'city', 'balance'])
                 ->orderBy('city');

    return PdfReport::of('Users Report', ['Date' => now()->format('d M Y')], $query, [
            'Name'    => 'name',
            'Email'   => 'email',
            'City'    => 'city',
            'Balance' => 'balance',
        ])
        ->editColumn('Balance', [
            'displayAs' => fn ($result) => '$' . number_format((float) $result->balance, 2),
        ])
        ->showTotal(['Balance' => 'point'])
        ->groupBy('City')
        ->stream();
}

use SamuelTerra22\ReportGenerator\Facades\PdfReport;

$query = User::select(['name', 'email', 'city', 'balance']);

// Render and return the PDF response
$pdf = PdfReport::of('Sales Report', ['Period' => 'Jan 2025'], $query, [
        'Name'    => 'name',
        'Email'   => 'email',
        'City'    => 'city',
        'Balance' => 'balance',
    ])
    ->editColumn('Balance', [
        'class'     => 'right',
        'displayAs' => fn ($result) => number_format((float) $result->balance, 2),
    ])
    ->showTotal(['Balance' => 'point'])
    ->groupBy('City')
    ->setPaper('a4')
    ->setOrientation('landscape')
    ->setCss([
        '.head-content' => 'border-bottom: 2px solid #333;',
    ])
    ->make();

use SamuelTerra22\ReportGenerator\Facades\ExcelReport;

$query = User::select(['name', 'email', 'balance']);

// Standard version (uses Blade template)
ExcelReport::of('Financial Report', ['Quarter' => 'Q1 2025'], $query, [
        'Name'    => 'name',
        'Email'   => 'email',
        'Balance' => 'balance',
    ])
    ->editColumn('Balance', [
        'displayAs' => fn ($result) => number_format((float) $result->balance, 2),
    ])
    ->showTotal(['Balance' => 'point'])
    ->download('financial-report');

ExcelReport::of('Financial Report', ['Quarter' => 'Q1 2025'], $query, [
        'Name'    => 'name',
        'Email'   => 'email',
        'Balance' => 'balance',
    ])
    ->showTotal(['Balance' => 'point'])
    ->simple()
    ->download('financial-report');

use SamuelTerra22\ReportGenerator\Facades\CsvReport;

$query = User::select(['name', 'email', 'balance']);

CsvReport::of('User Export', ['Date' => now()->format('d M Y')], $query, [
        'Name'    => 'name',
        'Email'   => 'email',
        'Balance' => 'balance',
    ])
    ->editColumn('Balance', [
        'displayAs' => fn ($result) => number_format((float) $result->balance, 2),
    ])
    ->download('user-export');

PdfReport::of(string $title, array $meta, $query, array $columns)

// Explicit mapping
$columns = [
    'Full Name' => 'name',
    'Email'     => 'email',
];

// Automatic mapping (column name is converted to snake_case for the DB field)
$columns = ['Name', 'Email']; // maps to 'name', 'email'

// Closure-based columns (computed values)
$columns = [
    'Full Name' => fn ($row) => $row->first_name . ' ' . $row->last_name,
    'Email'     => 'email',
];

->editColumn('Balance', [
    'class'     => 'right bold',   // CSS class for the column (PDF/Excel)
    'displayAs' => fn ($result) => '$' . number_format((float) $result->balance, 2),
])

->editColumns(['Price', 'Tax', 'Total'], [
    'class'     => 'right',
    'displayAs' => fn ($result, $colName) => number_format((float) $result->{strtolower($colName)}, 2),
])

->formatColumn('price', 'currency', ['prefix' => 'R$', 'decimals' => 2])
->formatColumn('created_at', 'date', ['format' => 'd/m/Y'])
->formatColumn('rate', 'percentage', ['decimals' => 1])
->formatColumn('active', 'boolean', ['true' => 'Active', 'false' => 'Inactive'])
->formatColumn('quantity', 'number', ['decimals' => 0, 'thousands_separator' => '.'])

->formatColumns(['Price', 'Total'], 'currency', ['prefix' => '$'])

// Single group
->groupBy('City')

// Multiple groups
->groupBy(['Country', 'City'])

->showTotal([
    'Balance'  => 'point',       // Shows: 1,234.56
    'Quantity' => 'QTY',         // Shows: QTY 1,234.56
    'Revenue'  => 'USD',         // Shows: USD 1,234.56
])

->showTotal([
    'amount'   => 'sum',       // Sum of all values (default)
    'quantity' => 'avg',       // Average
    'price'    => 'max',       // Maximum value
    'discount' => 'min',       // Minimum value
    'orders'   => 'count',     // Number of rows
    'balance'  => 'point',     // Sum, displayed without a label prefix
])

->conditionalFormat('amount', fn ($value) => $value > 1000, [
    'class'      => 'bold',
    'background' => '#ffcccc',
])
->conditionalFormat('status', fn ($value) => $value === 'Overdue', [
    'color'       => '#ff0000',
    'font-weight' => 'bold',
])

->conditionalFormat('name', fn ($value, $row) => $row->balance < 0, [
    'color' => 'red',
])

->onBeforeRender(function () {
    Log::info('Report generation started');
})
->onRow(function ($row, int $index) {
    // Fires for each row -- useful for progress tracking.    
})
->onAfterRender(function () {
    Log::info('Report rendering complete');
})
->onComplete(function () {
    Notification::send($admin, new ReportReadyNotification);
})

->setHeaderContent('Company Report', 'center')
->setHeaderContent('Confidential', 'left')

->setFooterContent('Page {page} of {pages}', 'right')
->setFooterContent('Printed: {date}', 'left')

->clearFooter()  // No footer

// Footer defaults (matches previous behavior)
'left'  => 'Date Printed: {date}'
'right' => 'Page {page} of {pages}'

// Header defaults: empty (no header)

use SamuelTerra22\ReportGenerator\Facades\ReportExporter;

$exporter = ReportExporter::of('Sales Report', $meta, $query, $columns)
    ->editColumn('amount', ['displayAs' => fn ($r) => '$' . $r->amount])
    ->formatColumn('date', 'date', ['format' => 'd/m/Y'])
    ->showTotal(['amount' => 'sum'])
    ->groupBy('region');

// Export to any format from the same definition:
$pdf   = $exporter->toPdf()->make();
$excel = $exporter->toExcel()->download('report');
$csv   = $exporter->toCsv()->download('report');

PdfReport::of(...)->cacheFor(60)->make();

->cacheFor(60)->cacheAs('monthly-sales-report')

->cacheFor(60)->cacheUsing('redis')

->cacheFor(60)->noCache()  // Caching disabled

->setPaper('letter')  // letter, legal, a3, a4, a5, etc.

->setOrientation('landscape')

->setCss([
    '.table'    => 'font-size: 11px;',
    'th'        => 'background-color: #4472C4; color: white;',
    'tr.even'   => 'background-color: #D9E2F3;',
])

->showHeader(false)

->showMeta(false)

->showNumColumn(false)

->limit(500)

->withoutManipulation()

->simple()

return [
    'flush'        => false,  // Enable output buffering flush during report generation
    'cache_store'  => null,   // Default cache store (null = Laravel default)
    'cache_prefix' => 'report-generator', // Prefix for auto-generated cache keys
];
bash
php artisan vendor:publish --tag="report-generator-config"
bash
php artisan vendor:publish --tag="report-generator-views"