Laravel database seeding

This is a very simple example of Laravel’s seeding to populate a new database with some data.

I often rollback and refresh my database migrations while I am developing in Laravel.  The thing is I generally need to have at least a user in the database in order to login and get access to the app.  So using the seed feature with Laravel is a big time saver for this.

So right out of the box there is file where information can be added to insert new information into the database by running a 'php artisan' command.

Open your app and find 'database\seeds\DatabaseSeeder.php'

public function run()
    {
        DB::table('users')->insert([
            'name' => 'Paul',
            'username' => 'admin',
            'email' => 'example@example.com',
            'password' => bcrypt('password'),
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date)'Y-m-d H:i:s')
        ]);

    }

Run: php artisan db:seed

It is also possible to run the seed with a migration as well.
php artisan migrate --seed
php artisan migrate:refresh --seed
After running the seed command (assuming no errors) your tables will be populated with the user details or whatever you need.

If you need to add multiple rows of data you will need to send an array of arrays like so:

 DB::table('users')->insert([
            [
              'name' => 'Paul',
              'username' => 'admin',
              'email' => 'example@example.com',
              'password' => bcrypt('password'),
              'created_at' => date('Y-m-d H:i:s'),
              'updated_at' => date)'Y-m-d H:i:s')
             ],
             [
              'name' => 'Bob',
              'username' => 'bobby',
              'email' => 'bob@example.com',
              'password' => bcrypt('bobspassword'),
              'created_at' => date('Y-m-d H:i:s'),
              'updated_at' => date)'Y-m-d H:i:s')
             ]
        ]);

Note: how both the rows of data are their own array but they are wrapped within an array.

It is also possible to insert using the model instance e.g.

User::insert([
      [
        //Your code here
       ],
      [
        //Etc
       ]
]);


Don’t forget to add use App\User above the class at the top of the page or change User to App\User above.

Oh, one last thing.  When you use insert the updated_at and created_at fields will not be populated, therefor using date('Y-m-d H:i:s') will remedy this. It is also possible to use the User::create however you can only pass a single row.

If you need to add more data, check out factories. They make adding heaps of data a cinch.

Leave a Reply

Your email address will not be published. Required fields are marked *