Skip to content

Instantly share code, notes, and snippets.

@hearsid
Last active September 15, 2015 10:10
Show Gist options
  • Save hearsid/c8290e03468f34e4edc7 to your computer and use it in GitHub Desktop.
Save hearsid/c8290e03468f34e4edc7 to your computer and use it in GitHub Desktop.
Laravel 5.1 : seed data from CSV files located in your {app}/database/seeds/CSV_FILES folder , first line of CSV must be table headings and consecutive lines the data to seed , no need to change the table structure in seeder , just change in CSV file .
<?php
use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;
class DatabaseSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
Model::unguard();
$this->call(AdminFoodIngredients::class);
Model::reguard();
}
}
define('CSV', base_path('database/seeds/CSV_FILES/'));
class AdminFoodIngredients extends Seeder {
public function run() {
$table_name = "admin_food_ingredients";
// delete the existing table
DB::table($table_name)->delete();
$wholeCSVData = array_map('str_getcsv', file(CSV . '/'.$table_name.'.csv'));
$i = "first_value";
foreach ($wholeCSVData as $single) {
if ($i == "first_value") {
foreach ($single as $key => $heading) {
$column_headings[] = $heading;
}
$i = "not_first_value" ;
continue ;
} // the first row in the csv file contains the headings
$theVal = [];
foreach ($single as $key => $row_value) {
// uncomment below when you have password in the csv and want to create a hash for it
// --useful for users table
// when inserting the password create the hash of the password
// and store the real password in another row
/* if($column_headings[$key] == "password") {
$theVal['password'] = Hash::make($row_value);
$theVal['password_real'] = $row_value ;
continue ;
}*/
$theVal[$column_headings[$key]] = $row_value;
} // after this loop we'll have one row prepared
DB::table($table_name)->insert($theVal);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment