Last active
June 29, 2021 09:45
-
-
Save ozmos/e2a61d421bb3a99550fd01172b7dcf76 to your computer and use it in GitHub Desktop.
Simple example of a Laravel Seeder class which seeds a table with data from a .csv file. Dependencies: parsecsv/php-parsecsv
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use Illuminate\Database\Migrations\Migration; | |
use Illuminate\Database\Schema\Blueprint; | |
use Illuminate\Support\Facades\Schema; | |
class CreatePropertiesTable extends Migration | |
{ | |
/** | |
* Run the migrations. | |
* | |
* @return void | |
*/ | |
public function up() | |
{ | |
Schema::create('properties', function (Blueprint $table) { | |
$table->id(); | |
$table->tinyText('name'); | |
$table->tinyText('address'); | |
$table->unsignedInteger('price'); | |
$table->unsignedSmallInteger('bedrooms'); | |
$table->unsignedSmallInteger('bathrooms'); | |
$table->unsignedSmallInteger('garages'); | |
$table->unsignedSmallInteger('frontage'); | |
$table->tinyText('image'); | |
$table->boolean('special'); | |
$table->boolean('featured'); | |
$table->timestamps(); | |
}); | |
} | |
/** | |
* Reverse the migrations. | |
* | |
* @return void | |
*/ | |
public function down() | |
{ | |
Schema::dropIfExists('properties'); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Database\Seeders; | |
use Illuminate\Database\Seeder; | |
use Illuminate\Support\Facades\DB; | |
use ParseCsv\Csv; | |
use Illuminate\Support\Facades\Storage; | |
class PropertySeeder extends Seeder | |
{ | |
/** | |
* Run the database seeds. | |
* | |
* @return void | |
*/ | |
public function run() | |
{ | |
// retrieve file | |
$csv = new Csv(); | |
$file = Storage::get('property-data.csv'); | |
$csv->parseFile($file); | |
// add data to table | |
$table = DB::table('properties'); | |
foreach ($csv->data as $index) { | |
$table->insert([ | |
'name' => $index['name'], | |
'address' => $index['address'], | |
'price' => $index['price'], | |
'bedrooms' => $index['bedrooms'], | |
'bathrooms' => $index['bathrooms'], | |
'garages' => $index['garages'], | |
'frontage' => $index['frontage'], | |
'image' => $index['image'], | |
'special' => $index['special'], | |
'featured' => $index['featured'], | |
]); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment