User::factory() on the Model class:
public function definition()
{
return [
'user_id' => \App\Models\User::factory(),
'body' => $this->faker->sentence,
];
}
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
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;
User::factory() on the Model class:
public function definition()
{
return [
'user_id' => \App\Models\User::factory(),
'body' => $this->faker->sentence,
];
}
Please or to participate in this conversation.