Laravel 8 database factory not found!

Laravel 8 database factory not found!

Posted on:November 23, 2020 at 10:00 AM

For some reason, if you change the model directory in laravel 8, you may face issues with creating the factory. It will show you the following error-

Class 'Database\Factories\Your\Directory\Models\ModelFactory' not found

It’s because of the way laravel 8 changes the factory.

Solution

Now in your, every model (that has factory) need to define a new method like that way-


protected static function newFactory()
    {
        return \Your\Directory\Database\Factories\ModelFactory::new();
    }

If you think your database factories will be in \Your\Directory permanently, I suggest you can change in the composer.json file-

"autoload": {
        "psr-4": {
            "App\\": "app/",
            "Database\\Factories\\": "your/directory/factories/",
            "Database\\Seeders\\": "database/seeders/",
            "Gleif\\Otrs\\": "otrs/"
        }
    },

Now run-

composer dumpautoload

Then on the model side, simply add-


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

Hope it will help you.