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

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

jdefez/laravel-csv
==================

laravel facade to read/write csv file

v0.5.1(4y ago)01.4kMITPHPPHP ^8.0

Since Sep 13Pushed 4y ago1 watchersCompare

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

READMEChangelogDependencies (3)Versions (15)Used By (0)

laravel-csv
===========

[](#laravel-csv)

This package provides a Laravel Facade for writing/reading Csv files.

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

[](#installation)

```
$ composer require jdefez/laravel-csv
```

Reading a Csv file
------------------

[](#reading-a-csv-file)

This utility class does not take hold of any data. It simply provides an iterator you can use to read your csv files.

### Basic usage

[](#basic-usage)

```
use Jdefez\LaravelCsv\Facades\Csv;

$file = new SplFileObject('path-to-my-file.csv', 'r');

if ($file->isReadable()) {
  $reader = Csv::reader($file);

  foreach ($reader->read() as $row) {

    // returns an array with the row's values

  }
}
```

### Reading the first row

[](#reading-the-first-row)

By default the first row is skipped. If you need to read the first row use `$reader->withHeadings()` method.

```
$reader = Csv::reader(new SplFileObject('path-to-my-file.csv', 'r'))
  ->withHeadings();
```

### Reader::keyByColumnName()

[](#readerkeybycolumnname)

The rows will be returned under the form of an associative arrays with the camel cased columns names as keys.

```
// Given a file
//
// lastname;firstname;date of birth
// Jacky;Terror;1875-02-12
// Julian;Nightmare;1815-11-11

$reader = Csv::reader(new SplFileObject('path-to-my-file.csv', 'r'))
  ->keyByColumnName()

foreach ($reader->read() as $row) {

  //array(
  //    "firstname" => "Jacky",
  //    "lastname" => "Terror",
  //    "date_of_birth" => "1875-02-12"
  //)

  //...

}
```

### Reader::toObject()

[](#readertoobject)

The rows will be casted to object using the kamel cased column names as properties.

```
// Given a file
//
// lastname;firstname;birthdate
// Jacky;Terror;1875-02-12
// Julian;Nightmare;1815-11-11

$reader = Csv::reader(new SplFileObject('path-to-my-file.csv', 'r'))
  ->toObject()

foreach ($reader->read() as $row) {

  //object(stdClass)#277 (2) {
  //    ["firstname"]=> string(4) "Jacky"
  //    ["lastname"]=> string(5) "Terror"
  //    ["date_of_birth"]=> string(13) "1875-02-12"
  //}

  // ...
}
```

### Mapping data

[](#mapping-data)

If you need a more sophisticated way to map your file. You could use `Reader::read(?callable $callback = null): Generator`

```
$iterator = Csv::reader(new SplFileObject('path-to-my-file.csv', 'r'))
  ->toObject()
  ->read(fn ($item) => UserDataBuilder::make(
    $item->firstname,
    $item->lastname,
    $item->date_of_birth,
  );

foreach ($iterator as $userData) {
  if ($userData->isValid()) {
    User::create($userData);
  }
}
```

### Fixing enconding

[](#fixing-enconding)

For this feature to work, you need to provide a list of expected encodings. They will be used to detect the current line encoding and if it has to be fixed. By default the Reader uses: `['ISO-8859-15', 'ISO-8859-1']`

```
// Fixing encoding from ISO to UTF-8

$reader = $reader->setToEncoding('UTF-8')
    ->setSearchEncodings(['ISO-8859-15', 'ISO-8859-1'])
    ->toObject();
```

Writing a Csv file
------------------

[](#writing-a-csv-file)

You can both work with `SplFileObject` or `SplTempFileObject`.

[This gist](https://gist.github.com/jdefez/e7624ec1b414bb82a430e3e5d29b59ec)demonstrates how you can use SplTempFileObject

### Writing an entire collection of data

[](#writing-an-entire-collection-of-data)

```
$collection = collect([
  ['Jacky', 'Terror', '1875-02-12'],
  ['Julian', 'Nightmare', '1815-11-11'],
  // ...
]);

Csv::writer()
  ->setFile(new SplFileObject('path-to-my-file.csv', 'w'))
  ->setColumns(['firstname', 'lastname', 'date of birth'])
  ->setData($collection)
  ->write();
```

### Writing line by line.

[](#writing-line-by-line)

```
$collection = collect([
  ['firstname', 'lastname', 'date_of_birth'],
  ['Jacky', 'Terror', '1875-02-12'],
  ['Julian', 'Nightmare', '1815-11-11'],
  // ...
]);

$writer = Csv::writer()->setFile(new SplFileObject('path-to-my-file.csv', 'w'));

$collection->each(fn ($line) => $writer->put($line));
```

### Mapping data

[](#mapping-data-1)

You can also map data when writing to the file with `Writer::write(callable $callback)`of `Writer::put(array|callable $row)`.

```
$models = Users::all();

$writer = Csv::writer(new SplFileObject('path-to-my-file.csv', 'w'));

$writer->setData($models)
  ->write(fn ($item) => [
    $item->firstname,
    $item->lastname,
    $item->birthday->format('Y-m-d')
  ]);

// Or iterate over the collection and append each line to the file.

$models->each(fn ($model) => $writer->put(fn () => [
    $model->firstname,
    $model->lastname,
    $model->birthday->format('Y-m-d')
]);
```

Todo:
-----

[](#todo)

**Reader:**

- Adding the ability to setup headings names. It could be a convinient way to map data. Especialy if we want to key by columns names or cast rows to stdClass when there are no columns names at all.

**Writer:**

- Writing to a given encoding

###  Health Score

26

—

LowBetter than 43% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity14

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity53

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

Recently: every ~43 days

Total

12

Last Release

1495d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/4343b37374e2cfcec3c3fad1537601a123656bc7be3983e49ff16e7947d65ee4?d=identicon)[jdefez](/maintainers/jdefez)

---

Top Contributors

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

---

Tags

laravelcsvwriterreader

###  Code Quality

TestsPHPUnit

### Embed Badge

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

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

###  Alternatives

[csanquer/colibri-csv

Lightweight and performant CSV reader and writer library

16161.7k4](/packages/csanquer-colibri-csv)[askdkc/livewire-csv

Add importing large CSV (and TSV) data feature to your Laravel models quickly and easily / Laravelにお手軽にCSVインポート機能(TSV含む、かつ大容量対応)を追加する凄いやつだよ🚀

171.4k](/packages/askdkc-livewire-csv)

PHPackages © 2026

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