PHPackages                             yavor-ivanov/csv-importer - 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. yavor-ivanov/csv-importer

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

yavor-ivanov/csv-importer
=========================

A CSV importer/exporter library for Laravel

1.1.0(9y ago)6322MITPHPPHP &gt;=5.4.0

Since Feb 2Pushed 9y ago17 watchersCompare

[ Source](https://github.com/dev-labs-bg/laravel-csv-importer)[ Packagist](https://packagist.org/packages/yavor-ivanov/csv-importer)[ RSS](/packages/yavor-ivanov-csv-importer/feed)WikiDiscussions master Synced 2mo ago

READMEChangelogDependenciesVersions (6)Used By (0)

About Laravel CSV Importer
==========================

[](#about-laravel-csv-importer)

A Laravel 4 library for importing/exporting CSV files into/out of database tables using Eloquent.

Note: This library is still early in development. You may find functionality which is inflexible, altogether, poorly documented. You are welcome to open issues, but my schedule may prevent me from reacting to them in a timely fashion. Nevertheless, I've open sourced it, as none of the Laravel CSV import/export packages could handle cross-CSV references.

Features
========

[](#features)

- Automatic importer/exporter registration
- CSV field preprocessing
- CSV field validation
- Cross CSV references (relationships)
- Automatic dependency resolution
- Rollback on error

Requirements
============

[](#requirements)

- PHP &gt;=5.4
- Laravel Framework &gt;= 4
- Composer
- RDBMS supported by Eloquent (Laravel ORM)

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

[](#installation)

To install, run: `php composer.phar require yavor-ivanov/csv-importer` in your laravel project root.

Alternatively, you can manually add `"yavor-ivanov/csv-importer": "dev-master"` to your `composer.json` under the `require` field.

Then, open `app/config/app.php` and add the following line in the `providers` array:

```
'providers' => array(
    'YavorIvanov\CsvImporter\CsvImporterServiceProvider',
)

```

The package is configured by default to look for:

- CSV files in `app/csv/files`
- Importers in `app/csv/importers/`
- Exporters in `app/csv/exporters/`
- Place CSV backups in `app/csv/files/backup/`

You'll need to create all these folders by running these commands:

```
mkdir -p app/csv/files/backup
mkdir app/csv/importers
mkdir app/csv/exporters

```

Examples
========

[](#examples)

I've set up an [examples repository](https://github.com/dev-labs-bg/laravel-csv-importer-examples) containing a Laravel 4 application with multiple importers and exporters.

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

[](#configuration)

The importer package comes preconfigured to look for CSV files and importer/exporter scripts in the `app/csv/files/` and `app/csv/importer` (and exporter) folders. If you wish to change this, you'll need to first get your own (application) copy of the configuration by running the following command:

`php artisan config:publish yavor-ivanov/csv-importer`

You will get a copy of the default configuration in `app/config/packages/yavor-ivanov/csv-importer/config.php`. Any changes to this file override the default configuration.

This is what the default config file looks like:

```
    'import' => [
        'file_match' => '*Importer.php',
        'register_path' => '\\csv\\importers\\',
        'class_match_pattern' => '/^(?!CSV)(.*)Importer$/',
        'default_csv_path' => '/csv/files/',
    ],
    'export' => [
        'file_match' = '*Exporter.php',
        'register_path' => '\\csv\\exporters\\',
        'class_match_pattern' => '/^(?!CSV)(.*)Exporter$/',
        'default_csv_path' => '/csv/files/',
    ],

```

The configuration options are ass follows:

- `file_match` - A regular expression that matches the file names to be considered importers/exporters. The package uses this to auto-register your importer/exporter classes.
- `register_path` - The location from which to include php scripts for the importers/exporters (relative to the `app` folder)
- `class_match_pattern` - The pattern by which the package distinguishes importers/exporters from other classes. This is used for the automatic importer/exporter registry.
- `default_csv_path` - The default directory the importer/exporter looks for CSV files (relative to the `app` folder)

Naming conventions
==================

[](#naming-conventions)

The package establishes the following file and class naming convention for the importer/exporters:

- All importers/exporters must be placed in their designated folders (`app/csv/importers` and `app/cs/exporters` by default). This location is controlled by the `register_path` configuration option.
- The PHP files themselves must end in `Importer.php` by default (`Exporter.php` for exporters). This is also controlled by the `file_match` configuration option.
- The classes in the files must match the `class_match_pattern`. Ending the class name with `Importer` or `Exporter` is enough for a valid class name by default.

In exchange for these limitation, the package is able to automatically register any importers/exporters that follow the convention. This allows you to:

- Create importer/exporter scripts and immediately use them in import/export commands
- Reference importers/exporters as dependencies of other importers/exporters and have the package automatically resolve them at runtime.
- Obtain a list of all registered importers/exporters.

Usage
=====

[](#usage)

### Commands

[](#commands)

The package comes with two commands `csv:import` and `csv:export`

The command format is: `csv:import  []`

Example usage: `php artisan csv:import categories` or `php artisan csv:import expenses validate`

The importer supports the following modes:

- `append` - Only adds **new** data to the table. Does not delete records that have been removed from the CSV, nor does it update records that have been changed.
- `overwrite` - Deletes everything in the table, and imports the CSV. Note: Overwrite mode does not propagate to dependencies, as this may result in a cascading delete of the whole database. As of this moment there is no way to override this behaviour.
- `update` - Some as append, but updates records in the table.
- `validate` - Checks the CSV file for errors. Does not write to the database.

The `mode` parameter is optional. The importer always runs in `append` mode if one is not supplied.

**NOTE:** As of the moment, the package doesn't support deleting records from the database when removed from a CSV file, as this is potentially error prone. A `prune` mode will be added in later versions that exclusively performs this operation. Right now, the only way to delete database records is with the `overwrite` option.

For more information on the command format, run `php artisan help csv:import`

### CSV format

[](#csv-format)

The only requirements for the CSV format are:

1. The CSV must include a header row
2. All columns in the header must be named
3. There must be at least one unique column
4. Cells which contain spaces must be quoted in the CSV output

An example of a valid CSV:

```
id,role_name
1,"super admin"
2,admin
3,moderator
4,user

```

idrole\_name1super admin2admin3moderator4user*(Table view)*### Database table format

[](#database-table-format)

idrole\_namecsv\_id4super admin15admin26moderator37user4In order to make use of caching, update mode, and cross-CSV references, the database table must include a `csv_id` column. This is used to find the database record for the corresponding CSV row.

### Model

[](#model)

The package uses Laravel's Eloquent ORM to read and write to the database. This means that there is no configuration needed for database access. This also allows you to use Eloquent features (such as observers, validators, custom properties, etc.) while importing and exporting.

In order to make sure the `csv_id` column autoincrements when creating new records outside the importer, you must use the `CSVReferenceTrait` in your model like so:

```
class UserRole extends Eloquent
{
    use YavorIvanov\CsvImporter\CSVReferenceTrait;

    protected $fillable = ['role_name'];
    protected $table = 'user_roles';

    // ...
}

```

The [`CSVReferenceTrait`](src/YavorIvanov/CsvImporter/CSVReferenceTrait.php) registers a `save` hook, which sets the proper `csv_id` for models saved without one.

**NOTE:** You **can** import to properties not listed in the `$fillable` array, as the importer turns off the Eloquent field guarding while importing. (Don't worry, it re-guards them when it's done.)

Importers
=========

[](#importers)

### Minimum configuration importer example

[](#minimum-configuration-importer-example)

The following is the minimum configuration needed to create an importer class, which creates a collection of `UserRole` models and imports them to the database, and supports `update` mode:

```
