Skip to content

Instantly share code, notes, and snippets.

@mikedfunk
Last active August 29, 2015 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikedfunk/50db50b025d83e2d56a1 to your computer and use it in GitHub Desktop.
Save mikedfunk/50db50b025d83e2d56a1 to your computer and use it in GitHub Desktop.
Laravel 4 CSV seeder class
<?php
/**
* CSV file seeder. put the csv in the same dir named like table_name.csv. Then
* set the tableName property. The run command picks up from there.
*
* @copyright MIT
*/
namespace InternetBrands\AutoClassifiedsPlatform\Common\Seeds;
use DB;
use Goodby\CSV\Import\Standard\Lexer;
use Goodby\CSV\Import\Standard\Interpreter;
use Goodby\CSV\Import\Standard\LexerConfig;
use ReflectionClass;
use Seeder;
/**
* CsvSeeder
*
* @author Michael Funk <mike@mikefunk.com>
*/
class CsvSeeder extends Seeder
{
/**
* table name
*
* @var string
*/
protected $tableName;
/**
* table field names
*
* @var array
*/
protected $fieldNames;
/**
* get the directory to the child class
*
* @return string
*/
protected function getDir()
{
$rc = new ReflectionClass(get_class($this));
return dirname($rc->getFileName());
}
/**
* run seeder
*
* @return void
*/
public function run()
{
// use the csv importer to insert data row by row
$lexer = new Lexer(new LexerConfig());
$interpreter = new Interpreter();
$i = 0;
$interpreter->addObserver(
function (array $row) use (&$i) {
// get the field names if it's the first row
if ($i === 0) {
$this->fieldNames = $row;
} else {
// assemble the new array with the field names as keys
$rowWithKeys = [];
foreach ($this->fieldNames as $key => $fieldName) {
$rowWithKeys[$fieldName] = $row[$key];
}
// insert this row
DB::table($this->tableName)->insert($rowWithKeys);
}
$i++;
}
);
// get the csv file and start the process
$fileName = $this->getDir() . '/' . $this->tableName . '.csv';
$lexer->parse($fileName, $interpreter);
$this->command->info($this->tableName . ' table seeded!');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment