PHPackages                             phpmystic/eloquent-exporter - 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. [Database &amp; ORM](/categories/database)
4. /
5. phpmystic/eloquent-exporter

ActiveLibrary[Database &amp; ORM](/categories/database)

phpmystic/eloquent-exporter
===========================

Export Eloquent models to CSV &amp; Excel with relationships support.

1.0.0(2mo ago)210↓66.7%MITPHPPHP ^8.0

Since Feb 18Pushed 2mo agoCompare

[ Source](https://github.com/mehdilight/eloquent-exporter)[ Packagist](https://packagist.org/packages/phpmystic/eloquent-exporter)[ RSS](/packages/phpmystic-eloquent-exporter/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (4)Versions (2)Used By (0)

Eloquent Exporter
=================

[](#eloquent-exporter)

Export Eloquent models to CSV &amp; Excel with a fluent API. Supports relationships, custom headers, formatting, chunking, and multi-sheet Excel files.

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

[](#requirements)

- PHP 8.0+
- Laravel 9, 10, 11, or 12

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

[](#installation)

```
composer require phpmystic/eloquent-exporter
```

The service provider is auto-discovered by Laravel.

Basic Usage
-----------

[](#basic-usage)

```
use PhpMystic\EloquentExporter\EloquentExporter;

// Export all users to CSV
EloquentExporter::for(User::class)
    ->columns(['name', 'email', 'created_at'])
    ->toCsv(storage_path('app/exports/users.csv'));

// Export all users to Excel
EloquentExporter::for(User::class)
    ->columns(['name', 'email', 'created_at'])
    ->toExcel(storage_path('app/exports/users.xlsx'));
```

### From a Query

[](#from-a-query)

```
EloquentExporter::query(User::where('is_active', true)->orderBy('name'))
    ->columns(['name', 'email'])
    ->toExcel('active-users.xlsx');
```

### Custom Headers

[](#custom-headers)

```
EloquentExporter::for(User::class)
    ->columns([
        'name' => 'Full Name',
        'email' => 'Email Address',
        'created_at' => 'Registered At',
    ])
    ->toCsv('users.csv');
```

Relationships
-------------

[](#relationships)

Relations are eager-loaded automatically to prevent N+1 queries.

### BelongsTo / HasOne (Dot Notation)

[](#belongsto--hasone-dot-notation)

```
EloquentExporter::for(User::class)
    ->columns([
        'name',
        'email',
        'department.name' => 'Department',
        'department.manager.name' => 'Manager',
    ])
    ->toCsv('users.csv');
```

NameEmailDepartmentManagerJohnEngineeringJaneSaraMarketingBob### HasMany (Comma-Separated)

[](#hasmany-comma-separated)

HasMany relationships are joined into a single cell by default.

```
EloquentExporter::for(User::class)
    ->columns([
        'name',
        'roles.name' => 'Roles',
    ])
    ->toCsv('users.csv');
```

NameRolesJohnAdmin, EditorSaraViewerUse a custom separator:

```
EloquentExporter::for(User::class)
    ->columns([
        'name',
        'tags.label' => 'Tags',
    ])
    ->separator('tags.label', ' | ')
    ->toCsv('users.csv');
```

### Expand Rows

[](#expand-rows)

Flatten HasMany relationships so each related record becomes its own row.

```
EloquentExporter::for(Order::class)
    ->columns([
        'id' => 'Order #',
        'customer.name' => 'Customer',
        'items.product.name' => 'Product',
        'items.quantity' => 'Qty',
        'items.price' => 'Price',
    ])
    ->expandRows('items')
    ->toExcel('orders.xlsx');
```

Order #CustomerProductQtyPrice1001JohnKeyboard179.991001JohnMouse229.991002SaraMonitor1399.99Nested expand is also supported:

```
EloquentExporter::for(Company::class)
    ->columns([
        'name' => 'Company',
        'departments.name' => 'Department',
        'departments.employees.name' => 'Employee',
        'departments.employees.email' => 'Email',
    ])
    ->expandRows('departments.employees')
    ->toCsv('company-roster.csv');
```

### BelongsToMany with Pivot Data

[](#belongstomany-with-pivot-data)

```
EloquentExporter::for(User::class)
    ->columns([
        'name',
        'projects.name' => 'Project',
        'projects.pivot.role' => 'Role',
        'projects.pivot.joined_at' => 'Joined',
    ])
    ->expandRows('projects')
    ->toExcel('team.xlsx');
```

Formatting Values
-----------------

[](#formatting-values)

```
EloquentExporter::for(Order::class)
    ->columns([
        'id' => 'Order #',
        'total' => 'Total',
        'created_at' => 'Date',
    ])
    ->format('total', fn ($value) => number_format($value, 2) . ' USD')
    ->format('created_at', fn ($value) => $value->format('Y-m-d'))
    ->toExcel('orders.xlsx');
```

Download Response
-----------------

[](#download-response)

Return a download response directly from a controller. The format is auto-detected from the file extension.

```
public function export()
{
    return EloquentExporter::for(User::class)
        ->columns(['name', 'email'])
        ->download('users.xlsx'); // or 'users.csv'
}
```

Chunking
--------

[](#chunking)

Process large datasets in chunks to reduce memory usage.

```
EloquentExporter::for(User::class)
    ->columns(['name', 'email'])
    ->chunk(1000)
    ->toCsv('all-users.csv');
```

Exportable Trait
----------------

[](#exportable-trait)

Add the `Exportable` trait to your model for a convenient shorthand.

```
use PhpMystic\EloquentExporter\Exportable;

class User extends Model
{
    use Exportable;
}
```

```
// From the model
User::exporter()
    ->columns(['name', 'email'])
    ->toCsv('users.csv');

// From a query builder
User::where('is_active', true)
    ->exporter()
    ->columns(['name', 'email'])
    ->download('active-users.xlsx');
```

Excel Sheets
------------

[](#excel-sheets)

### Custom Sheet Name

[](#custom-sheet-name)

```
EloquentExporter::for(User::class)
    ->columns(['name', 'email'])
    ->sheetName('Users')
    ->toExcel('users.xlsx');
```

### Multiple Static Sheets

[](#multiple-static-sheets)

```
EloquentExporter::query(User::where('is_active', true))
    ->columns(['name', 'email'])
    ->sheetName('Active Users')
    ->addSheet(
        User::where('is_active', false),
        ['name', 'email'],
        'Inactive Users'
    )
    ->toExcel('users.xlsx');
```

### Dynamic Sheets (One Sheet per Record)

[](#dynamic-sheets-one-sheet-per-record)

Generate a sheet for each record, with related data as rows.

```
EloquentExporter::for(User::class)
    ->sheetPerRecord('name')
    ->columns([
        'posts.title' => 'Title',
        'posts.status' => 'Status',
        'posts.views' => 'Views',
    ])
    ->toExcel('user-posts.xlsx');
```

This creates a sheet per user (named after `name`), each containing that user's posts.

Use a callback for custom sheet names:

```
EloquentExporter::for(User::class)
    ->sheetPerRecord(fn (User $user) => $user->name . ' (' . $user->email . ')')
    ->columns([
        'posts.title' => 'Title',
        'posts.status' => 'Status',
    ])
    ->toExcel('user-posts.xlsx');
```

### Sheet Meta

[](#sheet-meta)

Add parent record attributes as header rows above the data table.

```
EloquentExporter::for(User::class)
    ->sheetPerRecord('name')
    ->sheetMeta([
        'email' => 'Email',
        'department.name' => 'Department',
    ])
    ->columns([
        'posts.title' => 'Title',
        'posts.status' => 'Status',
    ])
    ->toExcel('user-posts.xlsx');
```

### Combining Static and Dynamic Sheets

[](#combining-static-and-dynamic-sheets)

```
EloquentExporter::for(User::class)
    ->columns(['name', 'email'])
    ->sheetName('Summary')
    ->addDynamicSheets(
        User::has('posts'),
        fn (User $user) => $user->name,
        ['posts.title' => 'Title', 'posts.status' => 'Status']
    )
    ->toExcel('full-report.xlsx');
```

API Reference
-------------

[](#api-reference)

MethodDescription`EloquentExporter::for(Model::class)`Create exporter for a model class`EloquentExporter::query($builder)`Create exporter from a query builder`->columns(array $columns)`Set columns to export (supports dot notation and custom headers)`->format(string $column, Closure $formatter)`Apply a formatter callback to a column`->separator(string $column, string $sep)`Set separator for HasMany comma-joined values`->expandRows(string $relation)`Flatten a HasMany/BelongsToMany into separate rows`->chunk(int $size)`Process records in chunks`->sheetName(string $name)`Set the Excel sheet name`->addSheet(Builder $query, array $columns, string $name)`Add an additional static sheet`->sheetPerRecord(string|Closure $key)`Create one sheet per record`->sheetMeta(array $columns)`Add parent record meta rows to dynamic sheets`->addDynamicSheets(Builder $query, Closure $name, array $columns)`Add dynamic sheets alongside static ones`->toCsv(string $path)`Export to a CSV file`->toExcel(string $path)`Export to an Excel (.xlsx) file`->download(string $filename)`Return a download response (format auto-detected)License
-------

[](#license)

MIT

###  Health Score

36

—

LowBetter than 82% of packages

Maintenance82

Actively maintained with recent releases

Popularity8

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity39

Early-stage or recently created project

 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

Unknown

Total

1

Last Release

89d ago

### Community

Maintainers

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

---

Top Contributors

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

---

Tags

laraveleloquentexcelcsvexporter

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/phpmystic-eloquent-exporter/health.svg)

```
[![Health](https://phpackages.com/badges/phpmystic-eloquent-exporter/health.svg)](https://phpackages.com/packages/phpmystic-eloquent-exporter)
```

###  Alternatives

[maatwebsite/excel

Supercharged Excel exports and imports in Laravel

12.7k144.3M712](/packages/maatwebsite-excel)[cyber-duck/laravel-excel

This package provides a way to export an Eloquent collection as an excel file and to import a Excel file as an Eloquent collection.

74225.0k](/packages/cyber-duck-laravel-excel)[cybercog/laravel-love

Make Laravel Eloquent models reactable with any type of emotions in a minutes!

1.2k302.7k1](/packages/cybercog-laravel-love)[cviebrock/eloquent-taggable

Easy ability to tag your Eloquent models in Laravel.

567694.8k3](/packages/cviebrock-eloquent-taggable)[reedware/laravel-relation-joins

Adds the ability to join on a relationship by name.

2121.2M13](/packages/reedware-laravel-relation-joins)[highsolutions/eloquent-sequence

A Laravel package for easy creation and management sequence support for Eloquent models with elastic configuration.

121130.3k](/packages/highsolutions-eloquent-sequence)

PHPackages © 2026

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