laravel seed multiple records with factory

Solutions on MaxInterview for laravel seed multiple records with factory by the best coders in the world

showing results for - "laravel seed multiple records with factory"
Javier
01 Jul 2017
1$ php artisan make:seeder ProductTableSeeder
2  //Creates a ProductTableSeeder file on Database/seeders
3  $php artisan make:Factory ProductFactory
4  //Creates a ProductTableSeeder file on Database/seeders
5  $php artisan make:model Product
6    
7  //Go to database/Factories/ProductFactory and paste:
8 <?php
9
10use Faker\Generator as Faker;
11
12$factory->define(\App\Product::class, function (Faker $faker) {
13    return [
14        'name' => $faker->name,
15	    'price' => $faker->randomFloat(2, 0, 8),
16	    'description' => $faker->text
17    ];
18});
19
20//Go to database/seeders/ProductTableSeeder and paste:
21<?php
22
23namespace Database\Seeders;
24
25use Illuminate\Database\Seeder;
26
27class ProductTableSeeder extends Seeder
28{
29    /**
30     * Run the database seeds.
31     *
32     * @return void
33     */
34    public function run()
35    {
36        //It creates 10 random insertions on the product table.
37        
38        \App\Models\Product::factory(10)->create();
39    }
40}
41//Go to database/seeders/DatabaseSeeder and paste:
42
43<?php
44
45namespace Database\Seeders;
46
47use Illuminate\Database\Seeder;
48
49class DatabaseSeeder extends Seeder
50{
51    /**
52     * Seed the application's database.
53     *
54     * @return void
55     */
56    public function run()
57    {
58        
59        $this->call(ProductTableSeeder::class);
60
61    }
62}
63//Finally run:
64$php artisan db:seed
65$php artisan tinker
66  //Check the data inserted on the model product.
67>>>App\Models\Product::all()
68  //Alternativelly you can also run:
69>>> DB::table('products')->get();
70