A
A
AlpineMilk2018-06-08 13:46:37
Laravel
AlpineMilk, 2018-06-08 13:46:37

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

1 answer(s)
G
Gleb Starkov, 2018-06-08
@AlpineMilk

$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')
        ]);
}

And to insert a date, it's better to use \Carbon\Carbon::now();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question