├── .gitattributes ├── .gitignore ├── config └── seederonce.php ├── composer.json ├── LICENSE ├── src ├── Contracts │ └── SeederOnceRepositoryInterface.php ├── Providers │ └── SeederOnceProvider.php ├── Commands │ └── InstallCommand.php ├── SeederOnce.php └── Repositories │ └── SeederRepository.php ├── .github └── workflows │ └── laravel.yml └── README.md /.gitattributes: -------------------------------------------------------------------------------- 1 | /tests export-ignore 2 | phpunit.xml export-ignore -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | vendor 2 | .phpunit.result.cache 3 | .vscode 4 | storage/* 5 | !storage/.gitkeep 6 | .env 7 | Makefile 8 | .gitmodules 9 | composer.lock 10 | .idea 11 | .phpunit.cache -------------------------------------------------------------------------------- /config/seederonce.php: -------------------------------------------------------------------------------- 1 | 'seeders', 5 | 6 | /** 7 | * If true db:seed command prints output 8 | * {class} already seeded ............... 15ms DONE 9 | */ 10 | 'print_already_seeded' => env('SEEDER_ONCE_PRINT_OUTPUT', false), 11 | ]; 12 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "kdabrow/seeder-once", 3 | "description": "Run your laravel seeders only once", 4 | "type": "package", 5 | "keywords": [ 6 | "php", 7 | "laravel", 8 | "seeder", 9 | "database" 10 | ], 11 | "license": "MIT", 12 | "authors": [ 13 | { 14 | "name": "Karol Dąbrowski", 15 | "email": "20278897+karoldabro@users.noreply.github.com", 16 | "homepage": "https://kdabrow.com" 17 | } 18 | ], 19 | "require": { 20 | "php": ">=8.2.0", 21 | "illuminate/console": "^10.0|^11.0|^12.0", 22 | "illuminate/database": "^10.0|^11.0|^12.0", 23 | "illuminate/support": "^10.0|^11.0|^12.0" 24 | }, 25 | "require-dev": { 26 | "orchestra/testbench": "^9.0" 27 | }, 28 | "autoload": { 29 | "psr-4": { 30 | "Kdabrow\\SeederOnce\\": "src" 31 | } 32 | }, 33 | "autoload-dev": { 34 | "psr-4": { 35 | "Kdabrow\\SeederOnce\\Tests\\": "tests" 36 | } 37 | }, 38 | "prefer-stable": true, 39 | "extra": { 40 | "laravel": { 41 | "providers": [ 42 | "Kdabrow\\SeederOnce\\Providers\\SeederOnceProvider" 43 | ] 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 karoldabro 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /src/Contracts/SeederOnceRepositoryInterface.php: -------------------------------------------------------------------------------- 1 | mergeConfigFrom($this->pathToConfig() . 'seederonce.php', 'seederonce'); 15 | 16 | $this->app->singleton( 17 | SeederOnceRepositoryInterface::class, 18 | function ($app) { 19 | return new SeederRepository($app['db'], $app['config']['seederonce.table_name']); 20 | } 21 | ); 22 | } 23 | 24 | public function boot() 25 | { 26 | if ($this->app->runningInConsole()) { 27 | $this->commands([ 28 | InstallCommand::class, 29 | ]); 30 | } 31 | 32 | $this->publishes([ 33 | $this->pathToConfig() . 'seederonce.php' => $this->app->configPath('seederonce.php'), 34 | ], 'seederonce.config'); 35 | } 36 | 37 | private function pathToConfig() 38 | { 39 | return __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/Commands/InstallCommand.php: -------------------------------------------------------------------------------- 1 | seederRepository = $seederRepository; 42 | } 43 | 44 | /** 45 | * Execute the console command. 46 | * 47 | * @return mixed 48 | */ 49 | public function handle() 50 | { 51 | $this->seederRepository->setConnection($this->input->getOption('database')); 52 | if ($this->seederRepository->existsTable()) { 53 | return $this->info("Table with seeders already exists"); 54 | } 55 | 56 | $this->seederRepository->createTable(); 57 | 58 | $this->info("Seeders table has been created successfully."); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /.github/workflows/laravel.yml: -------------------------------------------------------------------------------- 1 | name: tests 2 | 3 | on: 4 | push: 5 | branches: [ "master" ] 6 | pull_request: 7 | branches: [ "master" ] 8 | 9 | jobs: 10 | tests84: 11 | 12 | runs-on: ubuntu-latest 13 | 14 | steps: 15 | - uses: shivammathur/setup-php@15c43e89cdef867065b0213be354c2841860869e 16 | with: 17 | php-version: '8.4' 18 | - uses: actions/checkout@v3 19 | - name: Install Dependencies 20 | run: composer install -q --no-ansi --no-interaction --no-scripts --no-progress --prefer-dist 21 | - name: Create Database 22 | run: | 23 | mkdir -p database 24 | touch database/database.sqlite 25 | - name: Execute tests (Unit and Feature tests) via PHPUnit 26 | env: 27 | DB_CONNECTION: testing 28 | DB_DATABASE: database/database.sqlite 29 | run: vendor/bin/phpunit 30 | 31 | tests83: 32 | 33 | runs-on: ubuntu-latest 34 | 35 | steps: 36 | - uses: shivammathur/setup-php@15c43e89cdef867065b0213be354c2841860869e 37 | with: 38 | php-version: '8.3' 39 | - uses: actions/checkout@v3 40 | - name: Install Dependencies 41 | run: composer install -q --no-ansi --no-interaction --no-scripts --no-progress --prefer-dist 42 | - name: Create Database 43 | run: | 44 | mkdir -p database 45 | touch database/database.sqlite 46 | - name: Execute tests (Unit and Feature tests) via PHPUnit 47 | env: 48 | DB_CONNECTION: testing 49 | DB_DATABASE: database/database.sqlite 50 | run: vendor/bin/phpunit 51 | 52 | tests82: 53 | 54 | runs-on: ubuntu-latest 55 | 56 | steps: 57 | - uses: shivammathur/setup-php@15c43e89cdef867065b0213be354c2841860869e 58 | with: 59 | php-version: '8.2' 60 | - uses: actions/checkout@v3 61 | - name: Install Dependencies 62 | run: composer install -q --no-ansi --no-interaction --no-scripts --no-progress --prefer-dist 63 | - name: Create Database 64 | run: | 65 | mkdir -p database 66 | touch database/database.sqlite 67 | - name: Execute tests (Unit and Feature tests) via PHPUnit 68 | env: 69 | DB_CONNECTION: testing 70 | DB_DATABASE: database/database.sqlite 71 | run: vendor/bin/phpunit -------------------------------------------------------------------------------- /src/SeederOnce.php: -------------------------------------------------------------------------------- 1 | resolve($class); 31 | 32 | $name = get_class($seeder); 33 | 34 | if ($silent || ! isset($this->command)) { 35 | $seeder->__invoke($parameters); 36 | } else { 37 | $result = $seeder->__invoke($parameters); 38 | 39 | if (Config::get('seederonce.print_already_seeded') || $result !== false) { 40 | $this->printResult($name, $result); 41 | } 42 | } 43 | 44 | static::$called[] = $class; 45 | } 46 | 47 | return $this; 48 | } 49 | 50 | private function printResult($name, $result) 51 | { 52 | if ($result === false) { 53 | $name = $name . " already seeded"; 54 | } 55 | 56 | with(new Task($this->command->getOutput()))->render( 57 | $name, 58 | $result, 59 | ); 60 | } 61 | 62 | /** 63 | * Run the database seeds. 64 | * 65 | * @return mixed 66 | * 67 | * @throws \InvalidArgumentException 68 | */ 69 | public function __invoke(array $parameters = []) 70 | { 71 | if (!method_exists($this, 'run')) { 72 | throw new InvalidArgumentException('Method [run] missing from ' . get_class($this)); 73 | } 74 | 75 | $repository = $this->resolveSeederOnceRepository(); 76 | 77 | if (!$repository->existsTable()) { 78 | $repository->createTable(); 79 | } 80 | 81 | $name = get_class($this); 82 | 83 | if ($repository->isDone($name) && $this->seedOnce) { 84 | return false; 85 | } 86 | 87 | $callback = fn () => isset($this->container) 88 | ? $this->container->call([$this, 'run'], $parameters) 89 | : $this->run(...$parameters); 90 | 91 | if ($this->seedOnce) { 92 | $repository->add($name); 93 | } 94 | 95 | $uses = array_flip(class_uses_recursive(static::class)); 96 | 97 | if (isset($uses[WithoutModelEvents::class])) { 98 | $callback = $this->withoutModelEvents($callback); 99 | } 100 | 101 | return $callback(); 102 | } 103 | 104 | private function resolveSeederOnceRepository(): SeederOnceRepositoryInterface 105 | { 106 | return app(SeederOnceRepositoryInterface::class); 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

2 | GitHub Workflow Status (branch) 3 | Packagist Version 4 | Packagist Downloads 5 | Scrutinizer code quality (GitHub/Bitbucket) 6 |

7 | 8 | # Laravel Seeder Once 9 | This library allows you to run your Laravel seeders only once.
No matter how many times artisan command `db:seed` is called. Done seeders will never be executed again. 10 | 11 | ## How it works 12 | Works similarly to migrations. First creates table in database, then logs all seeds that extend abstract class `Kdabrow\SeederOnce\SeederOnce`. In nutshell this will prevent to execute method run() if was executed in the past. Mechanism of logging data into database is heavily inspired by Laravel migration mechanism from package illuminate/database. 13 | 14 | ## How to use it 15 | 16 | ### 1. Install it 17 | 18 | By composer: 19 | 20 | | php | laravel / lumen | seeder-once | 21 | |--------------------|-----------------|----------------------------------------------------| 22 | | 8.2, 8.3, 8.4 | 12.0 | ```composer require "kdabrow/seeder-once: ^6.0"``` | 23 | | 8.2, 8.3 | 10.0, 11.0 | ```composer require "kdabrow/seeder-once: ^5.0"``` | 24 | | 8.1, 8.2 | 10.0 | ```composer require "kdabrow/seeder-once: ^4.0"``` | 25 | | 8.0, 8.1 | 9.21 | ```composer require "kdabrow/seeder-once: ^3.0"``` | 26 | | 7.3, 7.4, 8.0 | 8.0, 9.0 | ```composer require "kdabrow/seeder-once: ^2.2"``` | 27 | | 7.2, 7.3, 7.4, 8.0 | 6.0, 7.0 | ```composer require "kdabrow/seeder-once: ^1.2"``` | 28 | 29 | In Lumen do not forget to register provider in bootstrap/app.php 30 | ```php 31 | $app->register(Kdabrow\SeederOnce\Providers\SeederOnceProvider::class); 32 | ``` 33 | 34 | ### 2. Create seeders table in database 35 | Use this command: 36 | ``` bash 37 | php artisan db:install 38 | ``` 39 | This step is optional. Trait SeederOnce detects if table exists. If not, creates it automatically. 40 | 41 | ### 3. Extend seeders that you want to be run only once with SeederOnce 42 | 43 | So result should look like this: 44 | ```php 45 | use Kdabrow\SeederOnce\SeederOnce; 46 | 47 | class SomeSeeder extends SeederOnce 48 | { 49 | /** 50 | * Seed the application's database. 51 | * 52 | * @return void 53 | */ 54 | public function run() 55 | { 56 | // 57 | } 58 | } 59 | ``` 60 | This prevents to seed class SomeSeeder if was already seeded before. 61 | **Tip**: Always replace class Seeder with SeederOnce. Otherwise, `db:seed` command might print unexpected results. 62 | 63 | ## Configuration 64 | 65 | ### Run seeder many times 66 | It is possible to overwrite default functionality by change parameter $seedOnce to false: 67 | ```php 68 | use Kdabrow\SeederOnce\SeederOnce; 69 | 70 | class DatabaseSeeder extends SeederOnce 71 | { 72 | public bool $seedOnce = false; 73 | 74 | /** 75 | * Seed the application's database. 76 | * 77 | * @return void 78 | */ 79 | public function run() 80 | { 81 | // 82 | } 83 | } 84 | ``` 85 | Such seeder will run like normal laravel seeder (as many times as called). 86 | 87 | ### Configuration file 88 | It is possible to publish configuration file: 89 | ```shell 90 | php artisan vendor:publish --tag=seederonce.config 91 | ``` 92 | #### Table name 93 | Default table name is: seeders 94 | 95 | #### Console output 96 | By default, seeder-once changes output of db:seed console command. Seeders that were run in the past will not be printed in the command output. It's possible to change that behaviour in configuration or by env variable: 97 | ```shell 98 | SEEDER_ONCE_PRINT_OUTPUT=true 99 | ``` 100 | Output for already run seeders looks like this: 101 | ```shell 102 | Database\Seeders\SomeSeeder was already seeded ..................... DONE 103 | ``` -------------------------------------------------------------------------------- /src/Repositories/SeederRepository.php: -------------------------------------------------------------------------------- 1 | table = $table; 55 | $this->resolver = $resolver; 56 | } 57 | 58 | /** 59 | * Get a query builder for the migration table. 60 | * 61 | * @return \Illuminate\Database\Query\Builder 62 | */ 63 | protected function table() 64 | { 65 | return $this->getConnection()->table($this->table)->useWritePdo(); 66 | } 67 | 68 | /** 69 | * Get the connection resolver instance. 70 | * 71 | * @return \Illuminate\Database\ConnectionResolverInterface 72 | */ 73 | public function getConnectionResolver() 74 | { 75 | return $this->resolver; 76 | } 77 | 78 | /** 79 | * Resolve the database connection instance. 80 | * 81 | * @return \Illuminate\Database\Connection 82 | */ 83 | public function getConnection() 84 | { 85 | return $this->resolver->connection($this->connection); 86 | } 87 | 88 | /** 89 | * Database connection name 90 | * 91 | * @param string $name 92 | * 93 | * @return void 94 | */ 95 | public function setConnection($name) 96 | { 97 | $this->connection = $name; 98 | } 99 | 100 | /** 101 | * --------- 102 | * My interface 103 | * --------- 104 | */ 105 | 106 | /** 107 | * @inheritDoc 108 | */ 109 | public function isDone(string $fileName): bool 110 | { 111 | return !$this->table() 112 | ->select('*') 113 | ->where('name', '=', $fileName) 114 | ->get() 115 | ->isEmpty(); 116 | } 117 | 118 | /** 119 | * @inheritDoc 120 | */ 121 | public function add(string $fileName): bool 122 | { 123 | $table = $this->table(); 124 | 125 | return $table->insert([ 126 | 'name' => $fileName, 127 | 'created_at' => Carbon::now() 128 | ]); 129 | } 130 | 131 | /** 132 | * @inheritDoc 133 | */ 134 | public function all(): Collection 135 | { 136 | $table = $this->table(); 137 | 138 | return collect($table->get()); 139 | } 140 | 141 | /** 142 | * @inheritDoc 143 | */ 144 | public function createTable() 145 | { 146 | $schema = $this->getConnection()->getSchemaBuilder(); 147 | 148 | $schema->create(Config::get('seederonce.table_name'), function (Blueprint $blueprint) { 149 | $blueprint->increments('id'); 150 | $blueprint->string('name'); 151 | $blueprint->dateTime('created_at'); 152 | }); 153 | } 154 | 155 | /** 156 | * @inheritDoc 157 | */ 158 | public function existsTable(): bool 159 | { 160 | $schema = $this->getConnection()->getSchemaBuilder(); 161 | 162 | return $schema->hasTable(Config::get('seederonce.table_name')); 163 | } 164 | } 165 | --------------------------------------------------------------------------------