t0berius's avatar

Class 'Database\Factories\UserFactory' not found / laravel Factory

Using factories the first time:

database/factories/UserFactory.php

namespace Database\Factories;

use App\User;
use Illuminate\Database\Eloquent\Factories\Factory;

class UserFactory extends Factory
{
    protected $model = User::class;

    public function definition()
    {
        return [
            'name'                  => $faker->name,
            'password'              => bcrypt('testtest'),
            'created_at'            => \Carbon\Carbon::now(),
            'updated_at'            => \Carbon\Carbon::now(),

        ];
    }
}

User model:

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class User extends Authenticatable
{
    use HasFactory;
...
}

Controller:

use App\User;

$user = User::factory()->create();

Throwing:

Class 'Database\Factories\UserFactory' not found
Error…/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Factories/Factory.php650

Marked line return $factory::new();

public static function factoryForModel(string $modelName)
{
    $factory = static::resolveFactoryName($modelName);

    return $factory::new();
}
0 likes
5 replies
click's avatar
click
Best Answer
Level 35

Are you running Laravel 7 or earlier? Try running composer dump-autoload after you've created a new factory.

edit nvm, looking at your code it seems you use Laravel 8.

edit 2. Did you upgrade from an older version of Laravel to Laravel 8? If so you have to update your composer.json file so it understands the location of your factories.

See the difference in the autoload key between L7 and L8.

https://github.com/laravel/laravel/blob/7.x/composer.json

https://github.com/laravel/laravel/blob/master/composer.json

it should look like:

"autoload": {
        "psr-4": {
            "App\": "app/",
            "Database\Factories\": "database/factories/",
            "Database\Seeders\": "database/seeders/"
        }
    },
8 likes
benholmen's avatar

Thank you @click, you saved me some frustration. I had upgraded from 7 to 8 and ran into this error. Cheers!

knightLaravel's avatar

I have the same issue, but I started with Laravel 8. I using Laradock and trying to run:

php artisan ide:models

but get the error: Exception: Class 'Database\Factories\PostFactory' not found Could not analyze class App\Models\Post.

wadelp's avatar

Ran into this issue when trying to use a factory in a package. I solved it by overriding the HasFactory::newFactory() method.

class LegacyCategory extends Model
{
    use HasFactory;

    ...    

    /**
     * Create a new factory instance for the model.
     *
     * @return \Illuminate\Database\Eloquent\Factories\Factory
     */
    protected static function newFactory()
    {
        return new LegacyCategoryFactory();
    }			
}
2 likes

Please or to participate in this conversation.