PHPackages                             audunru/export-response - 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. audunru/export-response

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

audunru/export-response
=======================

Export Laravel JSON to responses to other formats, e.g. CSV

v5.0.0(1mo ago)24.5k↓25%MITPHPPHP ^8.3CI passing

Since Sep 17Pushed 1mo ago1 watchersCompare

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

READMEChangelog (10)Dependencies (23)Versions (31)Used By (0)

Export JSON responses from Laravel
==================================

[](#export-json-responses-from-laravel)

[![Build Status](https://github.com/audunru/export-response/actions/workflows/validate.yml/badge.svg)](https://github.com/audunru/export-response/actions/workflows/validate.yml)[![Coverage Status](https://camo.githubusercontent.com/c74b357ea715ad30d6f2998188b9b9f861d77a1d5201fb7aa26f42dcf66cf493/68747470733a2f2f636f766572616c6c732e696f2f7265706f732f6769746875622f617564756e72752f6578706f72742d726573706f6e73652f62616467652e7376673f6272616e63683d6d61696e)](https://coveralls.io/github/audunru/export-response?branch=main)

Currently supported:

- CSV
- XLSX
- XML

Installation
============

[](#installation)

Step 1: Install with Composer
-----------------------------

[](#step-1-install-with-composer)

```
composer require audunru/export-response
```

Depending on which formats you want to export to, you will have to install additional packages:

FormatPackageCSV[spatie/simple-excel](https://github.com/spatie/simple-excel)XLSX[spatie/simple-excel](https://github.com/spatie/simple-excel)XML[spatie/array-to-xml](https://github.com/spatie/array-to-xml)Step 2: Add middleware to your routes
-------------------------------------

[](#step-2-add-middleware-to-your-routes)

To allow exports for all your API endpoints, add middleware to `Kernel.php`:

```
'api' => [
    'throttle:api',
    \Illuminate\Routing\Middleware\SubstituteBindings::class,
    \audunru\ExportResponse\Middleware\ExportCsv::class,
    \audunru\ExportResponse\Middleware\ExportXlsx::class,
    \audunru\ExportResponse\Middleware\ExportXml::class,
],
```

To add it to one particular API resource, you can use this in `api.php`:

```
Route::apiResource('documents', DocumentController::class)
    ->middleware([
        ExportCsv::class,
        ExportXlsx::class,
        ExportXml::class
    ])
    ->name('documents');
```

You can specify an array key which will be used to retrieve the data. "Dot" notation is supported.

```
Route::apiResource('documents', DocumentController::class)
    ->middleware([
        ExportCsv::with([
            'key' => 'data',
        ]),
        ExportXlsx::with([
            'key' => 'data',
        ]),
        ExportXml::class::with([
            'key' => 'data',
        ]),
    ])
    ->name('documents');
```

You can also add the middleware to the `$middlewareGroups` and `$routeMiddleware` arrays in `app/Http/Kernel.php`:

```
protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],

    'api' => [
        'throttle:api',
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
        // Add ExportCsv middleware to all requests. "data" is the name of
        // the key to retrieve using "dot" notation.
        'csv:data',
    ],
];

protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
    'can' => \Illuminate\Auth\Middleware\Authorize::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
    'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
    'csv' => \audunru\ExportResponse\Middleware\ExportCsv::class,
];
```

### Exporting from controller

[](#exporting-from-controller)

Instead of using middleware, you can perform the export in the controller:

```
class ProductController extends Controller
{
    public function csv()
    {
        $products = Product::all();

        return $products->toCsv('filename.csv');
    }
```

Lazy collections are also supported:

```
class ProductController extends Controller
{
    public function csv()
    {
        $products = Product::lazy();

        return $products->toCsv('filename.csv');
    }
```

Please use lazy collections when you can. During testing, using `Product::lazy()` to export 10,000 products took about 2MB of memory, compared to 44 MB of memory using `Product::all()`. Both exports took the same amount of time (around 45 seconds).

Step 3: Exporting a response
----------------------------

[](#step-3-exporting-a-response)

In order to retrieve an API response as CSV instead of JSON, send a request to your API with the `Accept` header set to `text/csv`.

For XML, set the header to `application/xml`.

For XLSX, set the header to `application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`.

Configuration
=============

[](#configuration)

Publish the configuration file by running:

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

Development
===========

[](#development)

Testing
-------

[](#testing)

Run tests:

```
composer test
```

###  Health Score

54

—

FairBetter than 97% of packages

Maintenance89

Actively maintained with recent releases

Popularity25

Limited adoption so far

Community11

Small or concentrated contributor base

Maturity76

Established project with proven stability

 Bus Factor2

2 contributors hold 50%+ of commits

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 ~68 days

Recently: every ~32 days

Total

25

Last Release

56d ago

Major Versions

v0.5.0 → v1.0.02023-07-18

v1.0.1 → v2.0.02024-05-17

v2.0.8 → v3.0.02025-06-10

v3.0.4 → v13.x-dev2026-03-24

v4.0.1 → v5.0.02026-03-24

PHP version history (4 changes)v0.1.0PHP ^8.0

v1.0.0PHP ^8.1

v2.0.0PHP ^8.2

v4.0.1PHP ^8.3

### Community

Maintainers

![](https://www.gravatar.com/avatar/444043228e007e4f695d18a30380b811fb60077138f7c46f111f45a1b98e2f1c?d=identicon)[audunru](/maintainers/audunru)

---

Top Contributors

[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (52 commits)")[![audunru](https://avatars.githubusercontent.com/u/5163790?v=4)](https://github.com/audunru "audunru (39 commits)")[![github-actions[bot]](https://avatars.githubusercontent.com/in/15368?v=4)](https://github.com/github-actions[bot] "github-actions[bot] (13 commits)")[![semantic-release-bot](https://avatars.githubusercontent.com/u/32174276?v=4)](https://github.com/semantic-release-bot "semantic-release-bot (4 commits)")

---

Tags

csvexportjsonlaraveljsonlaravelexportcsv

###  Code Quality

TestsPHPUnit

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/audunru-export-response/health.svg)

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

###  Alternatives

[bfinlay/laravel-excel-seeder

Seed the database with Laravel using Excel, XLSX, XLS, CSV, ODS, Gnumeric, XML, HTML, SLK files

3944.4k](/packages/bfinlay-laravel-excel-seeder)[initred/laravel-tabula

laravel-tabula is a tool for liberating data tables trapped inside PDF files for the Laravel framework.

1418.6k](/packages/initred-laravel-tabula)

PHPackages © 2026

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