PHP code example of saroven / laravel-reportify

1. Go to this page and download the library: Download saroven/laravel-reportify 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/ */

    

saroven / laravel-reportify example snippets


namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Saroven\Reportify\Contracts\Reportable;
use Saroven\Reportify\Traits\HasReportify;
use App\Exports\UserExport;
use App\Models\User;

class UserController extends Controller implements Reportable
{
    use HasReportify;

    public function index(Request $request)
    {
        // Intercept export requests (e.g. ?export=pdfStream or ?export=excel)
        if ($request->has('export')) {
            $view = in_array($request->get('export'), ['pdfStream', 'pdf']) ? 'reports.users-pdf' : null;
            return $this->exportReport($request, 'User Directory Report', view: $view, dataProvider: UserExport::class);
        }

        $users = User::latest('id')->paginate(10);
        return view('users.index', compact('users'));
    }

    public function getExportData(array $payload, string $exportType, int|string|null $userId = null): mixed
    {
        return User::query()->get();
    }
}

namespace App\Exports;

use App\Models\User;
use Saroven\Reportify\Contracts\Reportable;

class UserExport implements Reportable
{
    public function getExportData(array $payload, string $exportType, int|string|null $userId = null): mixed
    {
        $query = User::query();

        if (!empty($payload['search'])) {
            $search = $payload['search'];
            $query->where(function ($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                  ->orWhere('email', 'like', "%{$search}%")
                  ->orWhere('phone', 'like', "%{$search}%");
            });
        }

        // Return clean mapped attributes for spreadsheet and plain text exports
        return $query->latest('id')->get()->map(function (User $user) {
            return [
                'ID' => $user->id,
                'Name' => $user->name,
                'Email' => $user->email,
                'Role' => $user->role,
                'Department' => $user->department ?? '-',
                'Phone' => $user->phone ?? '-',
                'Status' => $user->status,
                'Created At' => $user->created_at ? $user->created_at->format('Y-m-d H:i:s') : '-',
            ];
        });
    }
}

use App\Exports\UserExport;
use Saroven\Reportify\Jobs\ProcessReportJob;

public function export(Request $request)
{
    ProcessReportJob::dispatch(
        requestData: $request->all(),
        type: 'users-report',
        title: 'Users Export',
        user: auth()->id(),
        view: 'reports.users-pdf',
        additionalData: ['orientation' => 'L'],
        dataProvider: UserExport::class
    );

    return back()->with('success', 'Export process started successfully.');
}

use Saroven\Reportify\Facades\Reportify;

public function print(Request $request)
{
    $users = User::where('status', 'active')->get();

    return Reportify::streamPdf(
        request: $request->all(),
        response: $users,
        title: 'Active Users List',
        type: 'active-users',
        view: 'reports.users-pdf',
        additionalData: [
            'orientation' => 'P',
            'paper_size' => 'A4',
            'headerHtml' => '<h2>Active Users Report</h2>'
        ]
    );
}

use Saroven\Reportify\Facades\Reportify;

// Export large dataset by automatically chunking & merging PDF parts
$pdfPath = Reportify::exportPdfChunk(
    request: $request->all(),
    response: $largeUserCollection,
    context: 'exports/pdf',
    title: 'Large User Directory Export',
    view: 'reports.users-pdf',
    additionalData: ['orientation' => 'P']
);

if ($request->has('export')) {
    $view = in_array($request->get('export'), ['pdfStream', 'pdf', 'pdfChunk']) ? 'reports.users-pdf' : null;
    return $this->exportReport($request, 'User Directory Report', view: $view, dataProvider: UserExport::class);
}

use Saroven\Reportify\Facades\Reportify;

// Export Excel (.xlsx)
$excelPath = Reportify::exportExcel($request->all(), $data, 'exports/excel', 'Users List', 'reports.users-table');

// Export CSV (.csv)
$csvPath = Reportify::exportCsv($request->all(), $data, 'exports/csv', 'Users List');

// Export Text File (.txt) — first line is the column headings (row keys), columns joined by " | "
$txtPath = Reportify::exportTxt($request->all(), $data, 'exports/txt', 'Users List');

// Custom delimiter
$txtPath = Reportify::exportTxt($request->all(), $data, 'exports/txt', 'Users List', null, ['separator' => ',']);

// Export Multi-Part ZIP Package (.zip)
$zipPath = Reportify::prepareZip('pdf', $request->all(), $largeData, 'exports/zips', 'User Statements', 'reports.statement-pdf');

namespace App\Providers;

use App\Models\Download;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Event;
use Saroven\Reportify\Events\ExportStarted;
use Saroven\Reportify\Events\ExportCompleted;
use Saroven\Reportify\Events\ExportFailed;

class AppServiceProvider extends ServiceProvider
{
    public function boot(): void
    {
        // 1. Export Started -> Record initial 'processing' status with unique exportId
        Event::listen(function (ExportStarted $event) {
            Download::create([
                'export_id' => $event->exportId,
                'user_id'   => $event->userId ?: null,
                'title'     => $event->title,
                'format'    => strtoupper($event->exportFormat),
                'status'    => 'processing',
            ]);
        });

        // 2. Export Completed -> Update status to 'completed' matched by unique exportId
        Event::listen(function (ExportCompleted $event) {
            $download = $event->exportId
                ? Download::where('export_id', $event->exportId)->first()
                : Download::where('title', $event->title)->where('status', 'processing')->latest('id')->first();

            if ($download) {
                $download->update([
                    'file_path' => $event->filePath,
                    'status'    => 'completed',
                ]);
            }
        });

        // 3. Export Failed -> Update status to 'failed' with error details
        Event::listen(function (ExportFailed $event) {
            $download = $event->exportId
                ? Download::where('export_id', $event->exportId)->first()
                : Download::where('title', $event->title)->where('status', 'processing')->latest('id')->first();

            if ($download) {
                $download->update([
                    'status' => 'failed',
                    'error'  => $event->errorMessage,
                ]);
            }
        });
    }
}

namespace App\Http\Controllers;

use App\Models\Download;
use Illuminate\Support\Facades\Storage;

class DownloadController extends Controller
{
    public function index()
    {
        $downloads = Download::latest('id')->paginate(10);
        return view('downloads.index', compact('downloads'));
    }

    public function download(Download $download)
    {
        $disk = config('reportify.storage_disk', 'public');
        return Storage::disk($disk)->download($download->file_path);
    }
}

return [
    'storage_disk'     => env('REPORTIFY_STORAGE_DISK', 'public'),
    'force_sync'       => (bool) env('REPORTIFY_FORCE_SYNC', false),
    'export_directory' => 'exports',
    'chunk_size'       => (int) env('REPORTIFY_CHUNK_SIZE', 2000),

    'mpdf' => [
        'backtrack_limit'       => '1000000000',
        'recursion_limit'       => '1000000000',
        'default_paper_size'    => 'A4',
        'default_orientation'   => 'P',
        'author'                => env('APP_NAME', 'Laravel'),
        'default_header_margin' => 28,
    ],

    'views' => [
        'pdf_header' => 'reportify::pdf-header',
        'pdf_footer' => 'reportify::pdf-footer',
        'empty_pdf'  => 'reportify::empty-pdf',
    ],
];

// Let Reportify auto-calculate but nudge everything 10mm lower
Reportify::exportPdf($request->all(), $data, 'exports/pdf', 'Invoice', 'reports.invoice', [
    'headerHtml'             => '<div><h2>Company</h2><p>Dhaka</p></div>',
    'additionalHeaderMargin' => 10,
]);

// Hard-set a fixed 45mm top margin (skip auto-calculation)
Reportify::exportPdf($request->all(), $data, 'exports/pdf', 'Report', 'reports.main', [
    'headerMargin' => 45,
]);

// Global default for all reports (config/reportify.php)
'mpdf' => [
    'default_header_margin' => 35,
],

// Web request  → redirect back with a `success` flash message
// API request  → JSON: { "message": "Export for 'X' is being processed...", "export_id": "uuid" }
// Queued exports say "is being processed"; sync exports (queue driver `sync`
// or `force_sync`) say "is ready" — both end with "Check Download Manager.".
return $this->exportReport($request, 'User Report', dataProvider: UserExport::class);

protected function reportifyExportResponse(string $title, ?string $exportId = null, bool $queued = true): mixed
{
    return response()->json([
        'status'  => 'queued',
        'message' => "'{$title}' export is queued.",
    ]);
}

   'connections' => [
       'database' => [
           'driver' => 'database',
           'table' => 'jobs',
           'queue' => 'default',
           'retry_after' => 90,
           'connection' => 'central',
       ],
   ],
   

   return $this->exportReport(
       $request,
       'Sales Report',
       additionalData: [
           'file_dir' => 'exports/' . tenant('id'),
       ],
       dataProvider: SalesExport::class
   );
   

   Event::listen(function (ExportCompleted $event) {
       tenancy()->central(function () use ($event) {
           Download::where('export_id', $event->exportId)->update([
               'file_path' => $event->filePath,
               'status'    => 'completed',
           ]);
       });
   });
   

'queues_are_tenant_aware_by_default' => true,

   return $this->exportReport(
       $request,
       'Sales Report',
       additionalData: [
           'file_dir' => 'exports/' . Tenant::current()->id,
       ],
       dataProvider: SalesExport::class
   );
   
bash
php artisan vendor:publish --tag=reportify-config
php artisan vendor:publish --tag=reportify-views
bash
php artisan reportify:make UserExport