diff --git a/src/Illuminate/Foundation/Console/ModelMakeCommand.php b/src/Illuminate/Foundation/Console/ModelMakeCommand.php index f4b4bd66df9e..e2a46a1bd3d4 100644 --- a/src/Illuminate/Foundation/Console/ModelMakeCommand.php +++ b/src/Illuminate/Foundation/Console/ModelMakeCommand.php @@ -205,6 +205,43 @@ protected function getDefaultNamespace($rootNamespace) return is_dir(app_path('Models')) ? $rootNamespace.'\\Models' : $rootNamespace; } + /** + * Build the class with the given name. + * + * @param string $name + * @return string + * + * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException + */ + protected function buildClass($name) + { + $replace = []; + + if ($this->option('factory')) { + $replace['{{ factoryDocBlock }}'] = $this->buildFactoryReplacements(); + } else { + $replace["\n {{ factoryDocBlock }}"] = ''; + } + + return str_replace( + array_keys($replace), array_values($replace), parent::buildClass($name) + ); + } + + /** + * Build the replacements for a factory DocBlock. + * + * @return string + */ + protected function buildFactoryReplacements() + { + $factoryNamespace = '\\Database\\Factories\\'.Str::studly($this->argument('name')).'Factory'; + + return << */ + EOT; + } + /** * Get the console command options. * diff --git a/src/Illuminate/Foundation/Console/stubs/model.stub b/src/Illuminate/Foundation/Console/stubs/model.stub index 2956d090e7ca..eb85079c53f1 100644 --- a/src/Illuminate/Foundation/Console/stubs/model.stub +++ b/src/Illuminate/Foundation/Console/stubs/model.stub @@ -7,5 +7,6 @@ use Illuminate\Database\Eloquent\Model; class {{ class }} extends Model { + {{ factoryDocBlock }} use HasFactory; } diff --git a/tests/Integration/Generators/ModelMakeCommandTest.php b/tests/Integration/Generators/ModelMakeCommandTest.php index 57ccdd6421e1..7e9f2cb80ab4 100644 --- a/tests/Integration/Generators/ModelMakeCommandTest.php +++ b/tests/Integration/Generators/ModelMakeCommandTest.php @@ -25,6 +25,11 @@ public function testItCanGenerateModelFile() 'class Foo extends Model', ], 'app/Models/Foo.php'); + $this->assertFileDoesNotContains([ + '{{ factoryDocBlock }}', + '/** @use HasFactory<\Database\Factories\FooFactory> */', + ], 'app/Models/Foo.php'); + $this->assertFilenameNotExists('app/Http/Controllers/FooController.php'); $this->assertFilenameNotExists('database/factories/FooFactory.php'); $this->assertFilenameNotExists('database/seeders/FooSeeder.php'); @@ -96,6 +101,8 @@ public function testItCanGenerateModelFileWithFactoryOption() 'namespace App\Models;', 'use Illuminate\Database\Eloquent\Model;', 'class Foo extends Model', + '/** @use HasFactory<\Database\Factories\FooFactory> */', + 'use HasFactory;', ], 'app/Models/Foo.php'); $this->assertFilenameNotExists('app/Http/Controllers/FooController.php');