laravel 8 insert multiple entries seeder code example
Example: 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();