From f1b98bc18bc32cb4244b8965d5c756f75604007f Mon Sep 17 00:00:00 2001 From: Duilio Palacios Date: Wed, 16 Sep 2020 11:42:35 +0100 Subject: [PATCH] Guess the model name when using the make:factory command --- .../Console/Factories/FactoryMakeCommand.php | 27 ++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/src/Illuminate/Database/Console/Factories/FactoryMakeCommand.php b/src/Illuminate/Database/Console/Factories/FactoryMakeCommand.php index aac32d84cf11..88b9b4a0bba4 100644 --- a/src/Illuminate/Database/Console/Factories/FactoryMakeCommand.php +++ b/src/Illuminate/Database/Console/Factories/FactoryMakeCommand.php @@ -62,7 +62,7 @@ protected function buildClass($name) { $namespaceModel = $this->option('model') ? $this->qualifyModel($this->option('model')) - : $this->qualifyModel('Model'); + : $this->qualifyModel($this->guessModelName($name)); $model = class_basename($namespaceModel); @@ -102,6 +102,31 @@ protected function getPath($name) return $this->laravel->databasePath().'/factories/'.str_replace('\\', '/', $name).'.php'; } + /** + * Guess the model name from the Factory name or return a default model name. + * + * @param string $name + * @return string + */ + protected function guessModelName($name) + { + if (Str::endsWith($name, 'Factory')) { + $name = substr($name, 0, -7); + } + + $modelName = $this->qualifyModel(class_basename($name)); + + if (class_exists($modelName)) { + return $modelName; + } + + if (is_dir(app_path('Models/'))) { + return 'App\Models\Model'; + } + + return 'App\Model'; + } + /** * Get the console command options. *