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

warpig's avatar
Level 12

Making factories in Laravel 8

How are factories made in Laravel 8? This is what im currently trying and I always get an error.

TweetFactory

    public function definition()
    {
        return [
            'user_id' => UserFactory::factory(),
            'body' => $this->faker->sentence,
        ];
    }

UserFactory

    public function definition()
    {
        return [
            'name' => $this->faker->name,
            'email' => $this->faker->unique()->safeEmail,
            'email_verified_at' => now(),
            'password' => 'yIXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
            'remember_token' => Str::random(10),
        ];
    }

In php artisan tinker I do the following: Tweet::factory()->create();

Message:

PHP Error:  Call to undefined method Database\Factories\UserFactory::factory() in /Users/eduard
ocoello/Projects/tweety/database/factories/TweetFactory.php on line 25

Both models do have this line: use Illuminate\Database\Eloquent\Factories\HasFactory;

0 likes
4 replies
tykus's avatar
tykus
Best Answer
Level 104

User::factory() on the Model class:

public function definition()
{
    return [
        'user_id' => \App\Models\User::factory(),
        'body' => $this->faker->sentence,
    ];
}
1 like
warpig's avatar
Level 12

I was able to fix it but by using use App\Models\User im guessing this does the same thing?

tykus's avatar

im guessing this does the same thing?

Correct; I wanted to be clear that the User class is the Model; whether you alias with use or fully qualify the class namespace is a matter of preference.

1 like

Please or to participate in this conversation.