PHPackages                             feijs/model-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. feijs/model-importer

ActiveLibrary

feijs/model-importer
====================

Directly import Eloquent models from excel files

330PHP

Since Aug 26Pushed 10y ago1 watchersCompare

[ Source](https://github.com/Feijs/model-importer)[ Packagist](https://packagist.org/packages/feijs/model-importer)[ RSS](/packages/feijs-model-importer/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependenciesVersions (2)Used By (0)

Model Importer
==============

[](#model-importer)

This package aims to provide a flexible and reusable solution to import Laravel Eloquent model data directly from excel and csv files

Features
--------

[](#features)

- Simple &amp; direct import
- Match **column titles** to **model attributes**
- Import related models
- Queued importing for multiple files

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

[](#installation)

Add the package in `composer.json` and run `composer update`

```
"require": {
	...
	"feijs/model-importer": "dev-master"
}
```

Add the ServiceProvider to the providers in `config\app.php`

```
'Feijs\ModelImporter\ModelImporterServiceProvider',
```

Usage
-----

[](#usage)

### Importable models

[](#importable-models)

Any model which can be imported should implement `Model\ImportableInterface` and use `Model\ImportableTrait`

```
use Feijs\ModelImporter\Model\ImportableTrait as ImportableModelTrait;

class Student extends Eloquent implements ImportableModel
{
	use ImportableModelTrait;
}
```

##### Attributes

[](#attributes)

Imported data is matched with existing data on a set of **match attributes**. These should be returned by the `getMatchAttributes` method.

```
	public function getMatchAttributes()
	{
		return ['student_id', 'phonenumber'];
	}
```

These **match attributes** should be mass assignable, and thus be included in the `fillable` array

```
	public $fillable = ['student_id', 'phonenumber', '...'];
```

Any attributes which should be importable, but not distict, should be returned by the `getImportAttributes`. These **import attributes** do not necassarily need to be included in the `fillable` array.

```
	public function getImportAttributes()
	{
		return ['name', 'email', 'street', 'zipcode', 'city'];
	}
```

##### Relations

[](#relations)

To import relation data, or link the newly imported models to existing relations, you can specify relations which should be imported. These should be returned by the `getImportRelations` method. Note that any models specified here should implement `Model\ImportableInterface` as well.

The following relations may be imported: `HasOne`, `HasMany`, `BelongsTo`, `BelongsToMany`.

```
    public function bankAccount(){
        return $this->hasMany('BankAccount');
    }

	public function getImportRelations() { return ['bankAccount']; }
```

### Import functionality

[](#import-functionality)

#### Initialisation

[](#initialisation)

```
	$importer = App::make('Feijs\ModelImporter\ModelImporter');
	$importer->setModel('Student');
```

#### CSV Import Settings

[](#csv-import-settings)

You may override the csv import settings and file encoding with the `setSettings` method.

```
	$importer->setSettings([
		'csv' => [
			'enclosure' => '"',		//Default
			'delimiter' => ","		//Default
		],
		'encoding' => 'UTF-8'		//Default

	]);
```

#### Input

[](#input)

Input for the importer should include at least:

- `file` (`Symfony\Component\HttpFoundation\File\UploadedFile`),
- `overwrite`: Update existing data? (`boolean`)
- `model`: an array of **model attribute** -&gt; **column title** translations
- `defaults`: an array of **models** -&gt; **attributes** -&gt; **default value**

All model names, attributes and column names should be in spinal-case (slugs)

#### Importing a single file

[](#importing-a-single-file)

```
	$success = $importer->import(Input::all());

	//Equivalent with example input:
	$success = $importer->import([
		'file' 		=> Input::file('data.csv'),
		'overwrite' => false,
		'student'	=> [
				'student_id' 	=> 'studentnumber',
				'phonenumber' 	=> 'mobile',
				'city' 			=> 'city',
		],
		'defaults'  => [
				'student' => [ 'city' => 'Amsterdam' ]
		]
	]);
```

#### Importing multiple files

[](#importing-multiple-files)

To import multiple files from a single request, use the `Distributor class` and the `importFiles` method. This will queue each file for import. Results will be written to the log.

- The first parameter is an array with files
- The second parameter is the same input array as on single file import (except the file)
- The third parameter is an array with csv &amp; encoding settings
- The fourth parameter is the classname of the model which is to be imported

```
	$distributor = App::make('Feijs\ModelImporter\Queue\Distributor;');

	$jobs_queued = distributor->importFiles(
							'file' 	=> Input::file('files'),
							Input::except('csv', 'encoding', 'files'),
							Input::only('csv', 'encoding'),
							'Student'
						);
```

### Output

[](#output)

#### Input Validation

[](#input-validation)

To get any validation errors (for the model-importer input) call the `validationErrors` method

```
	$importer->validationErrors()
```

#### Model validation

[](#model-validation)

To get errors encountered during the import (ex. from in-model validation) call the `errors` method

```
	$importer->errors()
```

#### Success

[](#success)

To find the number of data lines which were succesfully imported, call the `getImported` method

```
	$importer->getImported()
```

### Customization

[](#customization)

#### Model input slug

[](#model-input-slug)

By default the input should include the slugged model classname. To change this, override the `getPrefix` method

```
	public function getPrefix()
	{
		return snake_case(class_basename(get_class($this)));	//default
	}
```

#### Dates

[](#dates)

To change which attributes should be parsed as Carbon objects, override the `isDateAttribute` function

```
	public function isDateAttribute($key)
	{
		return in_array($key, $this->getDates());				//default
	}
```

###  Health Score

22

—

LowBetter than 22% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity10

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity43

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 88.9% 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.

### Community

Maintainers

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

---

Top Contributors

[![Feijs](https://avatars.githubusercontent.com/u/12059414?v=4)](https://github.com/Feijs "Feijs (8 commits)")[![GrahamCampbell](https://avatars.githubusercontent.com/u/2829600?v=4)](https://github.com/GrahamCampbell "GrahamCampbell (1 commits)")

### Embed Badge

![Health badge](/badges/feijs-model-importer/health.svg)

```
[![Health](https://phpackages.com/badges/feijs-model-importer/health.svg)](https://phpackages.com/packages/feijs-model-importer)
```

PHPackages © 2026

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