PHPackages                             vitorccs/laravel-csv - 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. vitorccs/laravel-csv

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

vitorccs/laravel-csv
====================

PHP Laravel package to create CSV files in a memory-optimized way

v2.0.0(1y ago)32214.1k↓14.7%6[2 issues](https://github.com/vitorccs/laravel-csv/issues)[1 PRs](https://github.com/vitorccs/laravel-csv/pulls)MITPHPPHP &gt;=8.0

Since Jan 11Pushed 1y ago1 watchersCompare

[ Source](https://github.com/vitorccs/laravel-csv)[ Packagist](https://packagist.org/packages/vitorccs/laravel-csv)[ RSS](/packages/vitorccs-laravel-csv/feed)WikiDiscussions master Synced 2d ago

READMEChangelog (4)Dependencies (3)Versions (5)Used By (0)

Laravel CSV
===========

[](#laravel-csv)

PHP Laravel package to export and import CSV files in a memory-optimized way.

Description
-----------

[](#description)

Export CSV files from *PHP arrays*, *Laravel Collections* or *Laravel Queries* and choose to prompt the user to download the file, store it in a Laravel disk or create the file in background as a Laravel Job.

Import CSV files from *Laravel Disks*, *local files*, *strings* or *resources* and choose to retrieve the full content or in small chunks.

The memory usage is optimized in this project by using [PHP streams](https://www.php.net/manual/en/intro.stream.php), which places the content in a temporary file (rather than PHP thread memory) and reads/writes content one line at a time.

NOTE: This project was inspired on  which is a great project and can handle many formats (Excel, PDF, OpenOffice and CSV). But since it uses PhpSpreadsheet, it is not optimized for handling large CSV files (thousands of records) causing the PHP memory exhaustion.

Upgrading from v1.0 to v2.0
---------------------------

[](#upgrading-from-v10-to-v20)

Version 2.0 adds the importing feature so the only required action is to change the importing namespace:

```
// v1.0 (old)
use Vitorccs\LaravelCsv\Concerns\Exportable;
use Vitorccs\LaravelCsv\Concerns\FromArray;
use Vitorccs\LaravelCsv\Concerns\FromCollection;
use Vitorccs\LaravelCsv\Concerns\FromQuery;
```

```
// v2.0 (new)
use Vitorccs\LaravelCsv\Concerns\Exportables\Exportable;
use Vitorccs\LaravelCsv\Concerns\Exportables\FromArray;
use Vitorccs\LaravelCsv\Concerns\Exportables\FromCollection;
use Vitorccs\LaravelCsv\Concerns\Exportables\FromQuery;
```

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

[](#requirements)

- PHP &gt;= 8.0
- Laravel &gt;= 6.x

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

[](#installation)

Step 1) Add composer dependency

```
composer require vitorccs/laravel-csv
```

Step 2) Publish the config file

```
php artisan vendor:publish --provider="Vitorccs\LaravelCsv\ServiceProviders\CsvServiceProvider" --tag=config
```

Step 3) Edit your local `config\csv.php` file per your project preferences

How to Export
-------------

[](#how-to-export)

Step 1) Create an Export class file as shown below

Note: you may implement *FromArray*, *FromCollection* or *FromQuery*

```
namespace App\Exports;

use App\User;
use Vitorccs\LaravelCsv\Concerns\Exportables\Exportable;
use Vitorccs\LaravelCsv\Concerns\Exportables\FromQuery;

class UsersExport implements FromQuery
{
    use Exportable;

    public function query()
    {
        return User::query()
            ->where('created_at', '>=', '2024-01-01 00:00:00');
    }
}
```

Step 2) The file can now be generated by using a single line:

```
# prompt the client browser to download the file
return (new UsersExport)->download('users.csv');
```

In case you want the file to be stored in the disk:

```
# will save the file in 's3' disk
return (new UsersExport)->store('users.csv', 's3');
```

You may also get the content as stream for better control over the output:

```
# will get the content in a stream (content placed in a temporary file)
return (new UsersExport)->stream();
```

For larger files, you may want to generate the file in background as a Laravel Job

```
use App\Jobs\NotifyCsvCreated;

# generate a {uuid-v4}.csv filename
$filename = CsvHelper::filename();

# will create a job to create and store the file in disk
# and afterwards notify the user
(new BillsExport())
    ->queue($filename, 's3')
    ->allOnQueue('default')
    ->chain([
        // You must create the Laravel Job below
        new NotifyCsvCreated($filename)
    ]);
```

Export - Data sources
---------------------

[](#export---data-sources)

Note: Only `FromQuery` can chunk results per `chunk_size` parameter from config file.

### Laravel Eloquent Query Builder

[](#laravel-eloquent-query-builder)

```
namespace App\Exports;

use App\User;
use Vitorccs\LaravelCsv\Concerns\Exportables\Exportable;
use Vitorccs\LaravelCsv\Concerns\Exportables\FromQuery;

class MyQueryExport implements FromQuery
{
    use Exportable;

    public function query()
    {
        return User::query();
    }
}
```

### Laravel Database Query Builder

[](#laravel-database-query-builder)

```
namespace App\Exports;

use App\User;
use Illuminate\Support\Facades\DB;
use Vitorccs\LaravelCsv\Concerns\Exportables\Exportable;
use Vitorccs\LaravelCsv\Concerns\Exportables\FromQuery;

class MyQueryExport implements FromQuery
{
    use Exportable;

    public function query()
    {
        return DB::table('users');
    }
}
```

### Laravel Collection

[](#laravel-collection)

```
namespace App\Exports;

use Vitorccs\LaravelCsv\Concerns\Exportables\Exportable;
use Vitorccs\LaravelCsv\Concerns\Exportables\FromCollection;

class MyCollectionExport implements FromCollection
{
    use Exportable;

    public function collection()
    {
        return collect([
            ['a1', 'b1', 'c1'],
            ['a2', 'b2', 'c2'],
            ['a3', 'b3', 'c3']
        ]);
    }
}
```

### Laravel LazyCollection

[](#laravel-lazycollection)

```
namespace App\Exports;

use App\User;
use Vitorccs\LaravelCsv\Concerns\Exportables\Exportable;
use Vitorccs\LaravelCsv\Concerns\Exportables\FromCollection;

class MyQueryExport implements FromCollection
{
    use Exportable;

    public function collection()
    {
        return User::cursor();
    }
}
```

### PHP Arrays

[](#php-arrays)

```
namespace App\Exports;

use Vitorccs\LaravelCsv\Concerns\Exportables\Exportable;
use Vitorccs\LaravelCsv\Concerns\Exportables\FromArray;

class MyArrayExport implements FromArray
{
    use Exportable;

    public function array(): array
    {
        return [
            ['a1', 'b1', 'c1'],
            ['a2', 'b2', 'c2'],
            ['a3', 'b3', 'c3']
        ];
    }
}
```

How to Import
-------------

[](#how-to-import)

Step 1) Create an Import class file as shown below

Note: you may implement *FromDisk*, *FromFile*, *FromResource* or *FromContents*

```
namespace App\Exports;

use Vitorccs\LaravelCsv\Concerns\Importables\Importable;
use Vitorccs\LaravelCsv\Concerns\Importables\FromDisk;

class UsersImport implements FromDisk
{
    use Importable;

    public function disk(): ?string
    {
        return 's3';
    }

    public function filename(): string
    {
        return 'users.csv';
    }
}
```

Step 2) The content can now be retrieved by using a single line:

```
# get the records in array format
return (new UsersImport)->getArray();
```

```
# in case the result is too large, you may receive small chunk of results
# at a time in your callback function, preventing memory exhaustion.
(new UsersImport)->chunkArray(function(array $rows, int $index) {
    // do something with the rows
    echo "Chunk $index has the following records:";
    print_r($rows);
});
```

Import - Data sources
---------------------

[](#import---data-sources)

### From string

[](#from-string)

```
namespace App\Imports;

use Vitorccs\LaravelCsv\Concerns\Importables\Importable;
use Vitorccs\LaravelCsv\Concerns\Importables\FromContents;

class MyContents implements FromContents
{
    use Importable;

    public function contents(): string
    {
        return "A1,B1,C1\nA2,B2,C2\n,A3,B3,C3";
    }
}
```

### From local File

[](#from-local-file)

```
namespace App\Imports;

use Vitorccs\LaravelCsv\Concerns\Importables\Importable;
use Vitorccs\LaravelCsv\Concerns\Importables\FromFile;

class MyFileImport implements FromFile
{
    use Importable;

    public function filename(): string;
    {
        return storage_path() . '/users.csv';
    }
}
```

### From resource

[](#from-resource)

```
namespace App\Imports;

use Vitorccs\LaravelCsv\Concerns\Importables\Importable;
use Vitorccs\LaravelCsv\Concerns\Importables\FromResource;

class MyResourceImport implements FromResource
{
    use Importable;

    public function resource()
    {
        $contents = "A1,B1,C1\nA2,B2,C2\n,A3,B3,C3";
        $resource = fopen('php://memory', 'w+');

        fputs($resource, $contents);

        return $resource;
    }
}
```

### From Laravel Disk

[](#from-laravel-disk)

```
namespace App\Exports;

use Vitorccs\LaravelCsv\Concerns\Importables\Importable;
use Vitorccs\LaravelCsv\Concerns\Importables\FromDisk;

class UsersImport implements FromDisk
{
    use Importable;

    public function disk(): ?string
    {
        return 'local';
    }

    public function filename(): string
    {
        return 'my_imports/users.csv';
    }
}
```

Implementations
---------------

[](#implementations)

The implementations below work with both Export and Import mode.

### Headings

[](#headings)

Implement `WithHeadings` for setting a heading to the CSV file.

```
use Vitorccs\LaravelCsv\Concerns\Exportables\Exportable;
use Vitorccs\LaravelCsv\Concerns\Exportables\FromArray;
use Vitorccs\LaravelCsv\Concerns\WithHeadings;

class UsersExport implements FromArray, WithHeadings
{
    use Exportable;

    public function headings(): array
    {
        return ['ID', 'Name', 'Email'];
    }
}
```

### Mapping rows

[](#mapping-rows)

Implement `WithMapping` if you either need to set the value of each column or apply some custom formatting.

```
use Vitorccs\LaravelCsv\Concerns\Exportables\Exportable;
use Vitorccs\LaravelCsv\Concerns\Exportables\FromArray;
use Vitorccs\LaravelCsv\Concerns\WithMapping;

class UsersExport implements FromArray, WithMapping
{
    use Exportable;

    public function map($user): array
    {
        return [
            $user->id,
            $user->name,
            $user->email ?: 'N/A'
        ];
    }
}
```

### Formatting columns

[](#formatting-columns)

Implement `WithColumnFormatting` to format date and numeric fields.

In export mode, the Date must be either a Carbon or a Datetime object, and the number must be any kind of numeric data (numeric string, integer or float).

In import mode, the string content must match with the formatting set (e.g: yyyy-mm-dd for dates).

The formatting preferences are set in the config file `csv.php`.

```
use Carbon\Carbon;
use Vitorccs\LaravelCsv\Concerns\Exportables\Exportable;
use Vitorccs\LaravelCsv\Concerns\Exportables\FromArray;
use Vitorccs\LaravelCsv\Concerns\WithColumnFormatting;
use Vitorccs\LaravelCsv\Enum\CellFormat;

class UsersExport implements FromArray, WithColumnFormatting
{
    use Exportable;

    public function array(): array
    {
        return [
            [ Carbon::now(), Carbon::now(), 2.50, 1.00 ],
            [ new DateTime(), new DateTime(), 3, 2.00 ]
        ];
    }

    public function columnFormats(): array
    {
        return [
            'A' => CellFormat::DATE,
            'B' => CellFormat::DATETIME,
            'C' => CellFormat::DECIMAL,
            'D' => CellFormat::INTEGER,
        ];
    }
}
```

### Limiting the results

[](#limiting-the-results)

Implement the method below if you need to limit the quantity of results to be exported/imported.

```
use Vitorccs\LaravelCsv\Concerns\Exportables\Exportable;
use Vitorccs\LaravelCsv\Concerns\Exportables\FromQuery;

class UsersExport implements FromQuery
{
    use Exportable;

    public function limit(): ?int
    {
        return 5000;
    }
}
```

License
-------

[](#license)

Released under the [MIT License](LICENSE).

###  Health Score

41

—

FairBetter than 87% of packages

Maintenance30

Infrequent updates — may be unmaintained

Popularity46

Moderate usage in the ecosystem

Community12

Small or concentrated contributor base

Maturity58

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 66.7% 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 ~306 days

Total

4

Last Release

714d ago

Major Versions

v1.0.1 → v2.0.02024-07-19

PHP version history (2 changes)v1.0.0PHP &gt;=7.4

v1.1.0PHP &gt;=8.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/2d5d2e771a97ac9dc5a1a1c8a18ec3cf97b5ea7872bfbc0fd62b060545cf6dfa?d=identicon)[vitorccs](/maintainers/vitorccs)

---

Top Contributors

[![vitorccs](https://avatars.githubusercontent.com/u/9891961?v=4)](https://github.com/vitorccs "vitorccs (8 commits)")[![Xint0-elab](https://avatars.githubusercontent.com/u/60675277?v=4)](https://github.com/Xint0-elab "Xint0-elab (4 commits)")

---

Tags

laravellaravel-packagephp8phplaravelexportcsv

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/vitorccs-laravel-csv/health.svg)

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

###  Alternatives

[maatwebsite/excel

Supercharged Excel exports and imports in Laravel

12.9k157.3M893](/packages/maatwebsite-excel)[techsemicolon/laravel-query-to-csv

Export the data from a query builder or raw select query into csv directly, eliminating overhead on php and in much less execution time

1010.6k](/packages/techsemicolon-laravel-query-to-csv)

PHPackages © 2026

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