Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

EvilAlex's avatar

Factory for model with custom namespace in Laravel 8

Hi all!

I have a little problem with new factories.

My models has custom namespaces like App\Domain\Product\Models\Product. And i want use a simple factory namespaces like \Database\Factories\ProductFactory.

When i try to make them from seed class:

Product::factory()->count(15)->create();

I get an error:

Class 'Database\Factories\Domain\Product\Models\ProductFactory' not found

But i dont want make so many folders, i want use Database\Factories\ProductFactory class.

When i make factory object manually, it works:

app(\Database\Factories\ProductFactory::class)->count(15)->create();

So, is there any way to use Model::factory() method and get \Database\Factories\ModelFactory object? Only delete new trait and make my own factory method?

Thanks!

0 likes
7 replies
gcwilliams's avatar

By the way you can also just call ProductFactory::new() instead of using the trait on the model itself.

3 likes
EvilAlex's avatar

Thank you! Solution by the link works well.

2 likes
Naysoewin's avatar

Hi @evilalex ,

I am also facing the same error , i see you fixed with above link. I am wondering if you could tell me how you fixed it with above link bro?. Thanks

cbj4074's avatar

@evilalex @gcwilliams Thanks for asking/answering this!

A simple inline example, for posterity:

class VelkartServiceProvider extends ServiceProvider
{
    public function boot()
    {
        Factory::guessFactoryNamesUsing(function ($name) {
            return (string) '\IndieHD\Velkart\Database\Factories\'.
                (class_basename($name)).
                'Factory';
        });
    }
}
1 like
carandclassic193779's avatar

I got to this question from DuckDuckGo-ing so apologies for the necro. I wanted to expand on the answer since the above only works if all your factories are in this different namespace, which is not the case always.

Per the docs you can define protected static newFactory() in a model that uses HasFactory and in that function return your custom factory, and that will work instead of doing the above in a service provider or every single test using your model.

7 likes

Please or to participate in this conversation.