Answer the question
In order to leave comments, you need to log in
How to simplify writing seeders?
Good afternoon! I created a seeder file that adds different categories, and as you can see it doesn't look very good. I have to prescribe every time DB::table('categories')->insert([
and so on, for all different values.
Question: Is there any way to make this easier? the values must always be different, so you can’t do this with a loop
<?php
use Illuminate\Database\Seeder;
class CategoriesTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
DB::table('categories')->insert([
'name' => 'PHP',
'created_at' => date ('Y-m-d H:i:s'),
'updated_at' => date ('Y-m-d H:i:s')
]);
DB::table('categories')->insert([
'name' => 'JavaScript',
'created_at' => date ('Y-m-d H:i:s'),
'updated_at' => date ('Y-m-d H:i:s')
]);
DB::table('categories')->insert([
'name' => 'HTML',
'created_at' => date ('Y-m-d H:i:s'),
'updated_at' => date ('Y-m-d H:i:s')
]);
DB::table('categories')->insert([
'name' => 'CSS',
'created_at' => date ('Y-m-d H:i:s'),
'updated_at' => date ('Y-m-d H:i:s')
]);
DB::table('categories')->insert([
'name' => 'Git',
'created_at' => date ('Y-m-d H:i:s'),
'updated_at' => date ('Y-m-d H:i:s')
]);
}
}
Answer the question
In order to leave comments, you need to log in
$names = [
'PHP',
'JavaScript',
'HTML',
// и другие
];
foreach($names as $name)
{
DB::table('categories')->insert([
'name' => $name,
'created_at' => date ('Y-m-d H:i:s'),
'updated_at' => date ('Y-m-d H:i:s')
]);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question