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?
New code examples in category PHP
-
PHP 2022-03-27 22:40:03 index:of curiosa 2019 mp4
-
PHP 2022-03-27 22:35:13 Dijkstra’s algorithm php
-
PHP 2022-03-27 22:35:12 get_declared_classes
-
PHP 2022-03-27 22:30:23 php move index of a value to first position in array
-
PHP 2022-03-27 22:25:01 wordpress get_date
-
PHP 2022-03-27 21:30:38 php shorten string with dots
-
PHP 2022-03-27 21:10:46 php header 500
-
PHP 2022-03-27 21:05:06 laravel schedule run
-
PHP 2022-03-27 20:25:12 Get page title, excerpt or content by id
-
PHP 2022-03-27 20:00:27 php convert date from dd/mm/yyyy to yyyy-mm-dd