1<?php
2
3namespace Database\Factories;
4
5use App\Models\Comment;
6use App\Models\Post;
7use Illuminate\Database\Eloquent\Factories\Factory;
8
9class CommentFactory extends Factory
10{
11 /**
12 * The name of the factory's corresponding model.
13 *
14 * @var string
15 */
16 protected $model = Comment::class;
17
18 /**
19 * Define the model's default state.
20 *
21 * @return array
22 */
23 public function definition()
24 {
25 $post_ids = Post::pluck('id')->toArray();
26
27 return [
28 'comment' => $this->faker->text(),
29 'post_id' => $post_ids[array_rand($post_ids)]
30 ];
31 }
32}
1For Laravel version 7.* and less
2factory(App\User::class, 3)->make();
3
4Use create method to persist them to the database:
5factory(App\User::class, 3)->create();