laravel seed multiple records with factory

$ php artisan make:seeder ProductTableSeeder
  //Creates a ProductTableSeeder file on Database/seeders
  $php artisan make:Factory ProductFactory
  //Creates a ProductTableSeeder file on Database/seeders
  $php artisan make:model Product
    
  //Go to database/Factories/ProductFactory and paste:
 <?php

use Faker\Generator as Faker;

$factory->define(\App\Product::class, function (Faker $faker) {
    return [
        'name' => $faker->name,
	    'price' => $faker->randomFloat(2, 0, 8),
	    'description' => $faker->text
    ];
});

//Go to database/seeders/ProductTableSeeder and paste:
<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;

class ProductTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        //It creates 10 random insertions on the product table.
        
        \App\Models\Product::factory(10)->create();
    }
}
//Go to database/seeders/DatabaseSeeder and paste:

<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
        
        $this->call(ProductTableSeeder::class);

    }
}
//Finally run:
$php artisan db:seed
$php artisan tinker
  //Check the data inserted on the model product.
>>>App\Models\Product::all()
  //Alternativelly you can also run:
>>> DB::table('products')->get();

Are there any code examples left?
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.
Creating a new code example
Code snippet title
Source