11. Create a factory:
2 php artisan make:factory ItemFactory --model=Item
3
4Import Illuminate\Database\Eloquent\Factories\HasFactory trait to your model:
5
6use Illuminate\Database\Eloquent\Factories\HasFactory;
7use Illuminate\Database\Eloquent\Model;
8
9class Item extends Model
10{
11 use HasFactory;
12
13 // ...
14}
15
162. Use it like this:
17
18 $item = Item::factory()->make(); // Create a single App\Models\Item instance
19
20 // or
21
22 $items = Item::factory()->count(3)->make(); // Create three App\Models\Item instances
23
243. Use create method to persist them to the database:
25
26 $item = Item::factory()->create(); // Create a single App\Models\Item instance and persist to the database
27
28 // or
29
30 $items = Item::factory()->count(3)->create(); // Create three App\Models\Item instances and persist to the database
31
1factory(App\User::class, 30)->create()->each(function($user) {
2
3 $entity = factory(App\Entity::class)->make();
4
5 $address = factory(App\Address::class)->create([
6 'entity_id' => $entity
7 ]);
8
9 $user->entities()->save($entity);
10});
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}