Last active
April 14, 2017 17:18
-
-
Save fastmover/bd586498c038fc65a158b600bd5e61df to your computer and use it in GitHub Desktop.
Add's artisan command: artisan db:clear - removes all tables in the current database.
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 App\Console\Commands; | |
| use DB; | |
| use Illuminate\Console\Command; | |
| use Illuminate\Support\Facades\Schema; | |
| class DBClear extends Command | |
| { | |
| /** | |
| * The name and signature of the console command. | |
| * | |
| * @var string | |
| */ | |
| protected $signature = 'db:clear'; | |
| /** | |
| * The console command description. | |
| * | |
| * @var string | |
| */ | |
| protected $description = 'Clear Database of all data'; | |
| /** | |
| * Create a new command instance. | |
| * | |
| * @return void | |
| */ | |
| public function __construct() | |
| { | |
| parent::__construct(); | |
| } | |
| /** | |
| * Execute the console command. | |
| * | |
| * @return mixed | |
| */ | |
| public function handle() | |
| { | |
| // | |
| if (!$this->confirm('CONFIRM DROP AL TABLES IN THE CURRENT DATABASE? [y|N]')) { | |
| exit('Drop Tables command aborted'); | |
| } | |
| $colname = 'Tables_in_' . env('DB_DATABASE'); | |
| $tables = DB::select('SHOW TABLES'); | |
| foreach($tables as $table) { | |
| $droplist[] = $table->$colname; | |
| } | |
| $droplist = implode(',', $droplist); | |
| DB::beginTransaction(); | |
| //turn off referential integrity | |
| //DB::statement('SET FOREIGN_KEY_CHECKS = 0'); | |
| DB::statement("DROP TABLE $droplist"); | |
| //turn referential integrity back on | |
| //DB::statement('SET FOREIGN_KEY_CHECKS = 1'); | |
| DB::commit(); | |
| $this->comment(PHP_EOL."If no errors showed up, all tables were dropped".PHP_EOL); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment