Database Seeding

Introduction:

Database seeds are a way of programmatically inserting a number of data into the database and one advantage to using them is you can quickly get dummy data into your app using seed classes. All seed classes are stored in the database/seeds directory. Seed classes may have any name you wish, but probably should follow some sensible convention, such as UsersTableSeeder

Normally we don’t need to create a new one, we can use the default database/seeds/DatabaseSeeder.php file for multiple seeders.

Now open the database/seeds/DatabaseSeeder.php file and adjust the run method to the following:

//Separately

public function run()

{

factory(App\User::class, 50)->create();

factory(App\Articles::class, 100)->create();

}

//Relational

public function run()

{

factory(App\User::class, 50)->create()->each(function ($u) {

$u->posts()->save(factory(App\Post::class)->make());

});

}

Now before these seed classes are useful they need instructions on what to insert. Let’s use model factories for that. By default, the db:seed command runs the DatabaseSeeder class.

You may also seed your database using the migrate:refresh command, which will also rollback and re-run all of your migrations. This command is useful for completely re-building your database:

php artisan migrate:refresh --seed

If we want to create a new seeder then we have to run below artisan command:

php artisan make:seeder UsersTableSeeder

After creating the seeder, open and paste into it as follows:

public function run()

{

factory(App\User::class, 50)->create();

}

Hence, we can create so many seeders and then we can run them from DatabaseSeeder class as follows:

public function run()

{

$this->call([

UsersTableSeeder::class,

PostsTableSeeder::class,

CommentsTableSeeder::class,

]);

}

However, you may use the --class option to specify a specific seeder class to run individually:

php artisan db:seed --class=UsersTableSeeder

 

The easiest way is to use tinker artisan command without using above mentioned process is as follows:

php artisan tinker

And then write as follows for seeds:

factory(App\User::class, 50)->create()

Or we can use only for check:

factory(App\User::class, 50)->make()

 

  • 249
  • 308
  • By Bablu Ahmed
  • Posted 1 year ago