Skip to content

Conversation

@sojeda
Copy link

@sojeda sojeda commented Apr 24, 2025

This PR extends Utils::getModelFactory() to support more flexible factory resolution scenarios, particularly for applications that:

Do not use the HasFactory trait on their Eloquent models,
Or define factories in standard locations, such as nested directories under database/factories/.

✅ Benefits

  • Non-invasive: Fully backward-compatible with existing behavior.
  • Supports advanced folder structures: Factory resolution works even if factories are organized by domain or module.
  • Improves DX: Makes the developer experience smoother for teams using custom factory setups or avoiding HasFactory for architectural reasons.
  • Safe fallback behavior: By returning null from resolveFactory(), the consuming code can choose how to react (e.g., skip, fallback, or throw).

What's New

  • Utils::resolveFactory()

    • Attempts to resolve the factory using the model’s factory() method (Laravel 8+ style).
    • If not available, recursively searches database/factories/** for {ModelName}Factory.php, even inside subdirectories.
    • Returns null if no factory is found, instead of throwing, giving the caller more control.
  • Utils::findFactoryClassForModel()

    • Recursively locates the correct factory file and builds its FQCN based on PSR-4 rules.
  • 🛠 Updated getModelFactory() to use the above methods and maintain compatibility with:

    • Legacy factory(Model::class) (Laravel <8),
    • state() definitions,
    • Nested relationships (has(), for(), hasAttached()).

image

@shalvah
Copy link
Contributor

shalvah commented May 1, 2025

Do you think you can add a test for this?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants