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

amir5's avatar
Level 7

testbench factory issues

I've created a model and factory with testbench make:model User -f, but when I call User::factory()...:

Error: Class "Database\Factories\Models\UserFactory" not found

Currently I solved it by defining newFactory method on model.

0 likes
11 replies
tykus's avatar

The Models segment in the namespace appears superfluous; where was the Factory class actually created?

tykus's avatar

@amir5 so the namespace is wrong? How’s the namespace been generated in the factory, and how is the Database namespace mapping in your composer.json?

amir5's avatar
Level 7

@tykus The UserFactory namespace is correct(Workbench\Database\Factories), and composer.json: "Workbench\\Database\\Factories\\": "workbench/database/factories/",

amir5's avatar
Level 7

@tykus steps to reproduce:

composer init
composer require --dev "orchestra/testbench"
vendor/bin/testbench workbench:install

testbench make:model Post -mf

Then testbench tinker and:

\Workbench\App\Models\Post::factory()->create()

-> Error Class "Database\Factories\Models\PostFactory" not found.

amir5's avatar
Level 7

@tykus I can fix it by defining newFactory

    protected static function newFactory()
    {
        return \Workbench\Database\Factories\PostFactory::new();
    }

But it probably should work by default when I'm using orchestral/testbench..

tykus's avatar

@amir5 agreed that it should work with laravel’s default namespaces; however the Factory class is being resolved it clearly incorrect.

What version of Testbench are you working with?

tykus's avatar
tykus
Best Answer
Level 104

@amir5 this

    protected static function newFactory()
    {
        return \Workbench\Database\Factories\PostFactory::new();
    }

is actually the correct approach since you have a non-standard namespace; the resolver cannot guess the correct namespace for your Factory class.

rawnato's avatar

Setup your TestCase.php like this.


use Illuminate\Database\Eloquent\Factories\Factory;

abstract class TestCase extends \Orchestra\Testbench\TestCase
{

    .......

    /**
     * @return void
     */
    protected function setUp(): void
    {
        parent::setUp();

        Factory::guessFactoryNamesUsing(function () {
            return 'Workbench\\Database\\Factories\\UserFactory';
        });
    }

    .......

}

works for me

rodrigogalura's avatar

To discover the factories inside your Workbench model, you need to enable them in the testbench.yaml file.

workbench:
  start: '/'
  install: true
  health: false
  discovers:
    web: false
    api: true
    factories: true // this is what you need

Please or to participate in this conversation.