Seed multiple rows at once laravel 5

PhpLaravelSchemaEloquentSeed

Php Problem Overview


I'm currently trying to seed my users table. If I try it like this with 2 rows, it fails. It works fine if I just use a single array instead of the 2 arrays inside the $users array to create some fake data.

What am I doing wrong, what is the proper way to do this?

class UserTableSeeder extends Seeder {

    public function run()
    {
        DB::table('users')->delete();

        $users = [
            ['id' => 1, 'name' => 'Stephan de Vries', 'username' => 'stephan', 'email' => '[email protected]', 'password' => bcrypt('carrotz124')],
            ['id' => 2, 'name' => 'John doe', 'username' => 'johnny', 'email' => '[email protected]', 'password' => bcrypt('carrotz1243')],
        ];

        User::create($users);
    }

}

Php Solutions


Solution 1 - Php

If you have to use the model you need a loop:

foreach($users as $user){
    User::create($user);
}

Otherwise you can just use DB::table() and insert:

DB::table('users')->insert($users);

Actually you can also call insert() on the model (the resulting query is the same)

User::insert($users);

Note if you choose the insert method you loose special Eloquent functionality such as timestamps and model events.

Solution 2 - Php

This works, for Laravel ^5

<?php

use Illuminate\Database\Seeder;

class UsersTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */

    public function run()
    {
    	// check if table users is empty
		if(DB::table('users')->count() == 0){

			DB::table('users')->insert([

				[
		            'name' => 'Administrator',
		            'email' => '[email protected]',
		            'password' => bcrypt('password'),
		            'created_at' => date('Y-m-d H:i:s'),
		            'updated_at' => date('Y-m-d H:i:s'),
				],
				[
					'name' => 'Agency',
		            'email' => '[email protected]',
		            'password' => bcrypt('password'),
		            'created_at' => date('Y-m-d H:i:s'),
		            'updated_at' => date('Y-m-d H:i:s'),
				],
				[
					'name' => 'End',
		            'email' => '[email protected]',
		            'password' => bcrypt('password'),
		            'created_at' => date('Y-m-d H:i:s'),
		            'updated_at' => date('Y-m-d H:i:s'),
				]

			]);
			
		} else { echo "\e[31mTable is not empty, therefore NOT "; }

    }
}

Solution 3 - Php

public function run()
{
    //
    for ($i=0; $i < 1000; $i++) { 
    	 DB::table('seo_contents')->insert([
    	    'title' => str_random(10),
    	    'content' => str_random(100),
    	    'created_at'=>date('Y-m-d H:i:s'),
    	    'updated_at'=>date('Y-m-d H:i:s'),
    	    
    	]);
    }
     
}

Solution 4 - Php

create() is used to store only one record. To store multiple records you should use insert() instead of create(). So the code will look like this:

class UserTableSeeder extends Seeder {

  public function run()
  {
    DB::table('users')->delete();

    $users = [
        ['id' => 1, 'name' => 'Stephan de Vries', 'username' => 'stephan', 'email' => '[email protected]', 'password' => bcrypt('carrotz124')],
        ['id' => 2, 'name' => 'John doe', 'username' => 'johnny', 'email' => '[email protected]', 'password' => bcrypt('carrotz1243')],
    ];

    User::insert($users);
  }

}

P.S. insert() function will not store timestamps. i.e.created_by & updated_by fields.

Solution 5 - Php

If anyone is struggling with this, I have been using the following since Laravel 5 and can confirm is still working in Laravel 7+...

class UserTableSeeder extends Seeder {

public function run()
{
    \DB::table('users')->delete();
    
    \DB::table('users')->insert(array (
        0 => 
          array (
                 'id' => 1,
                 'name' => 'Stephan de Vries',
                 'username' => 'stephan',
                 'email' => '[email protected]',
                 'password' => bcrypt('carrotz124'
         ),
        1 => 
          array (
                 'id' => 2,
                 'name' => 'John doe',
                 'username' => 'johnny',
                 'email' => '[email protected]',
                 'password' => bcrypt('carrotz1243'
         ),
     ));

}}

Solution 6 - Php

use truncate

<?php

use Illuminate\Database\Seeder;
use App\User;

class UsersTableSeeder extends Seeder
{
     /**
     * Run the database seeds.
     *
     * @return void
     */

  public function run()
    {

      User::truncate();

        $users =  [
            [
              'name' => 'Super Admin',
              'email' => '[email protected]',
              'password' => '123456',
            ],
            [
              'name' => 'Account Admin',
              'email' => '[email protected]',
              'password' => '13456',
            ],
            [
              'name' => 'Project Admin',
              'email' => '[email protected]',
              'password' => '13456',
            ],
            [
              'name' => 'Client Admin',
              'email' => '[email protected]',
              'password' => '13456',
            ]
          ];

          User::create($users);

    }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionStephan-vView Question on Stackoverflow
Solution 1 - PhplukasgeiterView Answer on Stackoverflow
Solution 2 - Phplewis4uView Answer on Stackoverflow
Solution 3 - PhpSimple TestView Answer on Stackoverflow
Solution 4 - PhpShrestharikeshView Answer on Stackoverflow
Solution 5 - PhpDCL_DevView Answer on Stackoverflow
Solution 6 - PhpMebrouki AmineView Answer on Stackoverflow