Laravel is unable to locate user factory

Viewed 2124

I'm building some tests in Laravel and I'm getting a very persistent error: InvalidArgumentException: Unable to locate factory for [App\Models\User].

The User class and UserFactory both exist and I believe I've used the correct namespacing. I have tried running composer dump autoload and to clear the cache and config but this has not worked.

My feature test:

<?php

namespace Tests\Feature;

use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithFaker;
use Tests\TestCase;

class ProjectsTest extends TestCase
{
    use WithFaker, RefreshDatabase;

    /** @test */
    public function only_authenticated_users_can_create_projects()
    {
        $attributes = factory('App\Models\Project')->raw();
        $this->post('/projects', $attributes)->assertRedirect('login');
    }
}

This is the ProjectFactory:

<?php

use Faker\Generator as Faker;

$factory->define(App\Models\Project::class, function (Faker $faker) {
    return [
        'title' => $faker->sentence,
        'description' => $faker->paragraph,
        'owner_id' => function () {
            return factory(App\Models\User::class)->create()->id;
        },
    ];
});

And here's the UserFactory:

<?php

namespace Database\Factories;

use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;

class UserFactory extends Factory
{
    /**
     * The name of the factory's corresponding model.
     *
     * @var string
     */
    protected $model = User::class;

    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition()
    {
        return [
            'name' => $this->faker->name,
            'email' => $this->faker->unique()->safeEmail,
            'email_verified_at' => now(),
            'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
            'remember_token' => Str::random(10),
        ];
    }
}

2 Answers

From your UserFactory class, I assume you are using Laravel 8.

The new way to call factories in Laravel 8 is

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

instead of the old way

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

I think you mixed Laravel 8 and 7 syntax in your ProjectFactory. I would recommend to delete your ProjectFactory and recreate it on Laravel 8 basis with the PHP artisan command: php artisan make:factory ProjectFactory. Then you would call the factory like this:

$project = Project::factory()->create();

Make sure your Project model uses the hasFactory; trait for this to work.

In my case I'd forgotten to change namespace in UserFactory file after moving the User model to Models directory.

Related