skip to Main Content

I have a User model in modules/Users/Models directory and UserFactory in the default database/factories directory.

I made this provider to avoid Class "DatabaseFactoriesModulesUsersModelsUserFactory" not found error when php artisan db:seed

namespace AppProviders;

use IlluminateSupportServiceProvider;
use IlluminateDatabaseEloquentFactoriesFactory;
use IlluminateSupportStr;

class FactoryServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        //
    }

    public function boot(): void
    {
        Factory::guessFactoryNamesUsing(function (string $model_name) {
            $namespace = 'Database\Factories\';
            $model_name = Str::afterLast($model_name, '\');
            return $namespace . $model_name . 'Factory';
        });
    }
}

Seeder calls this:
$users = User::factory()->count(10)->make();

But now I get Class "AppUser" not found error.
Please, tell me how to solve this?

3

Answers


  1. Chosen as BEST ANSWER

    Found a solution.

    Need to specify model in the factory: protected $model = ModulesUsersModelsUser::class; in the UserFactory


  2. When you call the factory in your seeder, make sure to use the full namespace of the User model. It looks like you’re calling User::factory() directly, which Laravel is trying to resolve based on the default App namesapce. Instead, you should reference the full namespace in your seeder file:

    use ModulesUsersModelsUser;
    
    Login or Signup to reply.
  3. use AppModelsUser; // or the correct namespace
    // Inside your seeder class
    $users = User::factory()->count(10)->make();
    

    Clear cache

    php artisan config:clear and php artisan cache:clear
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search