Search code examples
laraveldatabaselaravel-seeding

In laravel how to seed existing databse using array?


I want to seed existing database in my application. here is db with data in it: enter image description here

I made array in seeder and now I want to assign those values to my fields with one loop I guess;

This is migration:

public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->char('maker');
            $table->integer('model')->unique();
            $table->string('type');

        });
    }

And here is my seeder, I tried something but it isn't working. it says "Undefined array key "A""

public function run()
    {
        $array = ['A',  1232,   'PC',
                'A',    1233,   'PC',
                'A',    1276,   'Printer',
                'A',    1298,   'Laptop',
                'A',    1401,   'Printer',
                'A',    1408,   'Printer',
                'A',    1752,   'Laptop',
                'B',    1121,   'PC',
                'B',    1750,   'Laptop',
                'C',    1321,   'Laptop',
                'D',    1288,   'Printer',
                'D',    1433,   'Printer',
                'E',    1260,   'PC',
                'E',    1434,   'Printer',
                'E',    2112,   'PC',
                'E',    2113,   'PC'
        ];

        foreach ($array as $key => $item){

            Product::create([
                'maker' => $array[$item],
                'model' => $array[$item],
                'type' => $array[$item]
            ]);

        }
    }

Solution

  • use this function for insert all data

    for($i=0;i<size_of($array);$i++){
        if(($i%3)==0){
         DB::table('products')->insert([
            'maker' =>$array[$i],
            'model' => $array[$i+1],
            'type' => $array[$i+2]
        ]);
            
        }
    }