Creating a model with factory and seeder

969 0 0 0

Last Updated : 2024-04-18 16:08:32

Creating a model with factory and seeder

php artisan make:model Modelname -mf [This will create the model, migration and the factory as well]


php artisan make:seeder ModelnameSeeder

 


---------------------------------------------------


Modelname -> protected $fillable =[];
Modelname -> relationship methods

---------------------------------------------------


Migrations-> migrationFile and :
$table->id();
$table->foreignId('category_id')->contrained();
$table->string("name");
$table->text("description");
$table->integer("price");
$table->timestamps();

---------------------------------------------------
FactoryFile


$factory->define(Product::class, function (Faker $faker) {
return [
"category_id" => \App\Category::inRandomOrder()->first()->id,
"name" => $faker->word(),
"description" => $faker->paragraph,
"price" => rand(1000, 99999)
];

 


---------------------------------------------------
SeederFile


factory(\App\Product::class, 20)->create();

 


---------------------------------------------------
DatabaseSeederFile


$this->call(ProductSeeder::class);

 


---------------------------------------------------
now run


php artisan migrate:fresh --seed

Mohammed Anwar

Mohammed Anwar

Experienced technical lead PHP, MySQL and Laravel Developer for 15+ years, with proven ability to develop and create high-quality and optimized web applications. Great ability to build and optimize database design, schema and queries. Versed programing trainer and instructor delivering web courses and helping others to get into the field in a timely manner. Fast and eager learner for new technologies .