SeedCommand.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. <?php
  2. namespace Illuminate\Database\Console\Seeds;
  3. use Illuminate\Console\Command;
  4. use Illuminate\Database\Eloquent\Model;
  5. use Illuminate\Console\ConfirmableTrait;
  6. use Symfony\Component\Console\Input\InputOption;
  7. use Illuminate\Database\ConnectionResolverInterface as Resolver;
  8. class SeedCommand extends Command
  9. {
  10. use ConfirmableTrait;
  11. /**
  12. * The console command name.
  13. *
  14. * @var string
  15. */
  16. protected $name = 'db:seed';
  17. /**
  18. * The console command description.
  19. *
  20. * @var string
  21. */
  22. protected $description = 'Seed the database with records';
  23. /**
  24. * The connection resolver instance.
  25. *
  26. * @var \Illuminate\Database\ConnectionResolverInterface
  27. */
  28. protected $resolver;
  29. /**
  30. * Create a new database seed command instance.
  31. *
  32. * @param \Illuminate\Database\ConnectionResolverInterface $resolver
  33. * @return void
  34. */
  35. public function __construct(Resolver $resolver)
  36. {
  37. parent::__construct();
  38. $this->resolver = $resolver;
  39. }
  40. /**
  41. * Execute the console command.
  42. *
  43. * @return void
  44. */
  45. public function handle()
  46. {
  47. if (! $this->confirmToProceed()) {
  48. return;
  49. }
  50. $this->resolver->setDefaultConnection($this->getDatabase());
  51. Model::unguarded(function () {
  52. $this->getSeeder()->__invoke();
  53. });
  54. $this->info('Database seeding completed successfully.');
  55. }
  56. /**
  57. * Get a seeder instance from the container.
  58. *
  59. * @return \Illuminate\Database\Seeder
  60. */
  61. protected function getSeeder()
  62. {
  63. $class = $this->laravel->make($this->input->getOption('class'));
  64. return $class->setContainer($this->laravel)->setCommand($this);
  65. }
  66. /**
  67. * Get the name of the database connection to use.
  68. *
  69. * @return string
  70. */
  71. protected function getDatabase()
  72. {
  73. $database = $this->input->getOption('database');
  74. return $database ?: $this->laravel['config']['database.default'];
  75. }
  76. /**
  77. * Get the console command options.
  78. *
  79. * @return array
  80. */
  81. protected function getOptions()
  82. {
  83. return [
  84. ['class', null, InputOption::VALUE_OPTIONAL, 'The class name of the root seeder', 'DatabaseSeeder'],
  85. ['database', null, InputOption::VALUE_OPTIONAL, 'The database connection to seed'],
  86. ['force', null, InputOption::VALUE_NONE, 'Force the operation to run when in production'],
  87. ];
  88. }
  89. }