Created
March 27, 2015 22:49
-
-
Save jholl/2e3cf354da81ae965914 to your computer and use it in GitHub Desktop.
DatabaseSeeder to extend table cleanups/seeding ea. run (Laravel 5)
This file contains 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\Seeder; | |
use Illuminate\Database\Eloquent\Model; | |
use Illuminate\Filesystem\Filesystem; | |
class DatabaseSeeder extends Seeder { | |
/** | |
* Seeders to run. | |
* | |
* @return void | |
*/ | |
protected $seeders = [ | |
['TABLE1', 'SEEDERCLASS1'], | |
['TABLE2', 'SEEDERCLASS2'] | |
]; | |
/** | |
* Run the database seeds. | |
* | |
* @return void | |
*/ | |
public function run() | |
{ | |
Model::unguard(); | |
$this->cleanDatabase(); | |
$seeders = $this->seeders; | |
foreach ($seeders as $seedClass) | |
{ | |
$this->call($seedClass[1]); | |
} | |
} | |
/** | |
* Clean out DB tables for seeding | |
* | |
* @param null $table | |
*/ | |
protected function cleanDatabase($table = null) | |
{ | |
DB::statement('SET FOREIGN_KEY_CHECKS=0'); | |
if ($table) | |
{ | |
DB::table($table)->truncate(); | |
} | |
if (!$table) | |
{ | |
$tables = $this->seeders; | |
foreach ($tables as $table) | |
{ | |
DB::table($table[0])->truncate(); | |
} | |
} | |
DB::statement('SET FOREIGN_KEY_CHECKS=1'); | |
} | |
/** | |
* Get JSON file for seeding and return decoded | |
* | |
* @param $file | |
* @return mixed | |
* @throws \Illuminate\Contracts\Filesystem\FileNotFoundException | |
*/ | |
protected function getJSONDecoded($file) | |
{ | |
$filesystem = new Filesystem(); | |
return json_decode($filesystem->get(storage_path() . "/jsondata/" . $file)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
pick and choose, but most from Laracasts