Skip to content

Instantly share code, notes, and snippets.

@jholl
Created March 27, 2015 22:49
Show Gist options
  • Save jholl/2e3cf354da81ae965914 to your computer and use it in GitHub Desktop.
Save jholl/2e3cf354da81ae965914 to your computer and use it in GitHub Desktop.
DatabaseSeeder to extend table cleanups/seeding ea. run (Laravel 5)
<?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));
}
}
@jholl
Copy link
Author

jholl commented Mar 27, 2015

pick and choose, but most from Laracasts

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment