Reputation: 35
Laravel 8 has the default App/Models
directory for Model classes. The Illuminate\Database\Eloquent\Factories\Factory
has static function resolveFactoryName()
to resolve name of ModelNameFactory class
public static function resolveFactoryName(string $modelName)
{
$resolver = static::$factoryNameResolver ?: function (string $modelName) {
$modelName = Str::startsWith($modelName, 'App\\Models\\')
? Str::after($modelName, 'App\\Models\\')
: Str::after($modelName, 'App\\');
return static::$namespace.$modelName.'Factory';
};
return $resolver($modelName);
}
The function works properly only for App/ModelName
or App/Models/ModelName
if name of Model class, for example, is the Domain/Customers/Models/ModelName
, that function doesn't work properly. What is the best way to fix it?
Upvotes: 1
Views: 3559
Reputation: 1
Please put this in your model class in App\Models\ModelName
.
Make sure the ModelFactory
is the factory name.
protected static function newFactory()
{
return \Modules\Module\Database\Factories\ModelFactory::new();
}
Upvotes: 0
Reputation: 8242
As you can see here, there is a method called guessFactoryNamesUsing
which lets you tell Laravel how it should guess the name of your factories.
Add the following to your AppServiceProvider
:
use Illuminate\Database\Eloquent\Factories\Factory;
public function register()
{
Factory::guessFactoryNamesUsing(function ($class) {
return 'Database\\Factories\\' . class_basename($class) . 'Factory';
});
}
/**
* Specify the callback that should be invoked
* to guess factory names based on dynamic relationship names.
*
* @param callable $callback
* @return void
*/
public static function guessFactoryNamesUsing(callable $callback)
{
static::$factoryNameResolver = $callback;
}
Upvotes: 3