PHPackages                             philiprehberger/laravel-export - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [PDF &amp; Document Generation](/categories/documents)
4. /
5. philiprehberger/laravel-export

ActiveLibrary[PDF &amp; Document Generation](/categories/documents)

philiprehberger/laravel-export
==============================

Registry-based data export system for Laravel with pluggable format support. Ships with CSV and JSON exporters

v1.1.5(1mo ago)116[1 PRs](https://github.com/philiprehberger/laravel-export/pulls)MITPHPPHP ^8.2CI passing

Since Mar 6Pushed 1mo agoCompare

[ Source](https://github.com/philiprehberger/laravel-export)[ Packagist](https://packagist.org/packages/philiprehberger/laravel-export)[ Docs](https://github.com/philiprehberger/laravel-export)[ RSS](/packages/philiprehberger-laravel-export/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (6)Versions (8)Used By (0)

Laravel Export
==============

[](#laravel-export)

[![Tests](https://github.com/philiprehberger/laravel-export/actions/workflows/tests.yml/badge.svg)](https://github.com/philiprehberger/laravel-export/actions/workflows/tests.yml)[![Latest Version on Packagist](https://camo.githubusercontent.com/2c77d825e5751cde127c486eed3d0042a83c0e4253639497fc1a8724b1e08724/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f7068696c69707265686265726765722f6c61726176656c2d6578706f72742e737667)](https://packagist.org/packages/philiprehberger/laravel-export)[![License](https://camo.githubusercontent.com/57fcfc0f1dbafc70a0524fc82581149c7e28c174b0bb94c9f6e5a047d2444f1a/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f7068696c69707265686265726765722f6c61726176656c2d6578706f7274)](LICENSE)

Registry-based data export system for Laravel with pluggable format support. Ships with CSV and JSON exporters.

Requirements
------------

[](#requirements)

- PHP 8.2+
- Laravel 11 or 12

Installation
------------

[](#installation)

```
composer require philiprehberger/laravel-export
```

The service provider is auto-discovered via Laravel's package discovery.

Optionally publish the config file:

```
php artisan vendor:publish --tag=laravel-export-config
```

Usage
-----

[](#usage)

### Export a Collection to CSV

[](#export-a-collection-to-csv)

```
use PhilipRehberger\Export\Facades\Export;
use Illuminate\Support\Collection;

$data = collect([
    ['name' => 'Alice', 'email' => 'alice@example.com', 'plan' => 'pro'],
    ['name' => 'Bob',   'email' => 'bob@example.com',   'plan' => 'free'],
]);

$columns = [
    'name'  => 'Name',
    'email' => 'Email Address',
    'plan'  => 'Plan',
];

$csvString = Export::export($data, $columns, 'csv');
```

### Export a Collection to JSON

[](#export-a-collection-to-json)

```
$jsonString = Export::export($data, $columns, 'json');
```

### Download Response (CSV)

[](#download-response-csv)

Return a download response directly from a controller:

```
public function download(Request $request): Response
{
    $users = User::all();

    $data = $users->map(fn ($u) => [
        'name'       => $u->name,
        'email'      => $u->email,
        'created_at' => $u->created_at,
    ]);

    $columns = [
        'name'       => 'Name',
        'email'      => 'Email',
        'created_at' => 'Registered',
    ];

    return Export::download($data, $columns, 'csv', 'users');
    // Sends users.csv with Content-Disposition: attachment
}
```

### Stream Response (for large datasets)

[](#stream-response-for-large-datasets)

```
return Export::stream($data, $columns, 'csv', 'users');
// Returns a StreamedResponse
```

> **Note:** Filenames passed to `download()` and `stream()` are automatically sanitized — control characters, quotes, backslashes, and forward slashes are stripped. Empty filenames fall back to `"export"`.

### ExportableInterface on Models

[](#exportableinterface-on-models)

Implement `ExportableInterface` on your Eloquent model to let the service derive columns and filename automatically:

```
use PhilipRehberger\Export\Contracts\ExportableInterface;

class User extends Model implements ExportableInterface
{
    public function toExportArray(): array
    {
        return [
            'name'       => $this->name,
            'email'      => $this->email,
            'plan'       => $this->plan,           // enums are auto-unwrapped
            'created_at' => $this->created_at,     // Carbon dates are auto-formatted
        ];
    }

    public static function getExportColumns(): array
    {
        return [
            'name'       => 'Name',
            'email'      => 'Email Address',
            'plan'       => 'Plan',
            'created_at' => 'Registered',
        ];
    }

    public static function getExportFilename(): string
    {
        return 'users-export';
    }
}
```

Then export a collection of models:

```
$users = User::where('active', true)->get();

// Returns the CSV string
$csv = Export::exportModels($users, 'csv');

// Returns a download Response, filename derived from model
return Export::downloadModels($users, 'csv');

// Override filename
return Export::downloadModels($users, 'csv', 'active-users');
```

#### Automatic Value Transformations

[](#automatic-value-transformations)

`AbstractExportFormat` handles these transformations automatically inside `toExportArray` or when using raw collections:

TypeTransformation`BackedEnum``->value``Carbon\Carbon``->toDateTimeString()` (Y-m-d H:i:s)`array` / `object``json_encode()`### Creating a Custom Format Exporter

[](#creating-a-custom-format-exporter)

Implement `ExportFormatInterface` (or extend the provided `AbstractExportFormat` base class):

```
use Illuminate\Support\Collection;
use PhilipRehberger\Export\Formats\AbstractExportFormat;

class XmlExporter extends AbstractExportFormat
{
    public function export(Collection $data, array $columns, array $options = []): string
    {
        $rows = $this->transformData($data, $columns);

        $xml = new SimpleXMLElement('');
        foreach ($rows as $row) {
            $item = $xml->addChild('item');
            foreach ($row as $key => $value) {
                $item->addChild(preg_replace('/\s+/', '_', $key), htmlspecialchars((string) $value));
            }
        }

        return $xml->asXML();
    }

    public function getContentType(): string { return 'application/xml'; }
    public function getFileExtension(): string { return 'xml'; }
    public function getFormatName(): string { return 'xml'; }
}
```

Register it in a service provider:

```
use PhilipRehberger\Export\ExportFormatRegistry;

public function boot(ExportFormatRegistry $registry): void
{
    $registry->register(new XmlExporter);
}
```

Then use it exactly like the built-in formats:

```
Export::download($data, $columns, 'xml', 'report');
```

### Checking Available Formats

[](#checking-available-formats)

```
Export::supportsFormat('csv');       // true
Export::supportsFormat('excel');     // false (not registered)
Export::getAvailableFormats();       // ['csv', 'json']
Export::getFormatMetadata();         // [['name'=>'csv', 'extension'=>'csv', 'contentType'=>'text/csv; charset=UTF-8'], ...]
```

### Configuration Reference

[](#configuration-reference)

Published at `config/laravel-export.php`:

```
return [
    'csv' => [
        'delimiter'       => ',',
        'enclosure'       => '"',
        'include_bom'     => true,   // UTF-8 BOM for Excel compatibility
        'include_headers' => true,
    ],

    'json' => [
        'pretty_print'      => true,
        'include_metadata'  => false, // wraps output in {metadata:{}, data:[]}
    ],
];
```

#### Option Reference

[](#option-reference)

OptionFormatDefaultDescription`delimiter`CSV`,`Field separator`enclosure`CSV`"`String enclosure character`include_bom`CSV`true`Prepend UTF-8 BOM (improves Excel compatibility)`include_headers`CSV`true`Write column headers as the first row`pretty_print`JSON`true`Human-readable indented output`include_metadata`JSON`false`Wrap array in `{metadata, data}` envelopeOptions can be passed per-call to override the config defaults:

```
Export::export($data, $columns, 'csv', [
    'delimiter'   => ';',
    'include_bom' => false,
]);
```

API
---

[](#api)

### `Export` Facade / Service

[](#export-facade--service)

MethodDescription`Export::export(Collection $data, array $columns, string $format, array $options = []): string`Export data to a string in the given format`Export::download(Collection $data, array $columns, string $format, string $filename = 'export', array $options = []): Response`Return a download response`Export::stream(Collection $data, array $columns, string $format, string $filename = 'export', array $options = []): StreamedResponse`Return a streamed download response`Export::exportModels(Collection $models, string $format, array $options = []): string`Export a collection of `ExportableInterface` models`Export::downloadModels(Collection $models, string $format, ?string $filename = null, array $options = []): Response`Download a collection of `ExportableInterface` models`Export::supportsFormat(string $format): bool`Check whether a format is registered`Export::getAvailableFormats(): array`List all registered format names`Export::getFormatMetadata(): array`List format name, extension, and content type for each format### `ExportableInterface`

[](#exportableinterface)

MethodDescription`toExportArray(): array`Return the model as an associative array for export`getExportColumns(): array`Return column key → label mapping`getExportFilename(): string`Return the default export filename (without extension)Development
-----------

[](#development)

```
composer install
vendor/bin/phpunit
vendor/bin/pint --test
vendor/bin/phpstan analyse
```

License
-------

[](#license)

MIT

###  Health Score

41

—

FairBetter than 89% of packages

Maintenance89

Actively maintained with recent releases

Popularity10

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity51

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~2 days

Total

7

Last Release

53d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/cfd7d24cbbf32400fa13ce0bbe7a31edd2d66a6d4488eafdb3d64c5337bf0435?d=identicon)[philiprehberger](/maintainers/philiprehberger)

---

Top Contributors

[![philiprehberger](https://avatars.githubusercontent.com/u/8218077?v=4)](https://github.com/philiprehberger "philiprehberger (18 commits)")

---

Tags

jsonlaraveldataexportcsvdownload

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/philiprehberger-laravel-export/health.svg)

```
[![Health](https://phpackages.com/badges/philiprehberger-laravel-export/health.svg)](https://phpackages.com/packages/philiprehberger-laravel-export)
```

###  Alternatives

[maatwebsite/excel

Supercharged Excel exports and imports in Laravel

12.7k144.3M712](/packages/maatwebsite-excel)[highsolutions/laravel-lang-import-export

A Laravel package providing artisan commands to import and export language files from and to CSV.

25292.3k](/packages/highsolutions-laravel-lang-import-export)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
