Database: Seeding

    Laravel includes a simple method of seeding your database with test data using seed classes. All seed classes are stored in the directory. Seed classes may have any name you wish, but probably should follow some sensible convention, such as UsersTableSeeder, etc. By default, a DatabaseSeeder class is defined for you. From this class, you may use the call method to run other seed classes, allowing you to control the seeding order.

    To generate a seeder, execute the make:seeder Artisan command. All seeders generated by the framework will be placed in the database/seeds directory:

    As an example, let's modify the default DatabaseSeeder class and add a database insert statement to the run method:

    1. <?php
    2. use Illuminate\Database\Seeder;
    3. class DatabaseSeeder extends Seeder
    4. /**
    5. * Run the database seeds.
    6. *
    7. * @return void
    8. */
    9. public function run()
    10. {
    11. DB::table('users')->insert([
    12. 'name' => str_random(10),
    13. 'email' => str_random(10).'@gmail.com',
    14. ]);
    15. }
    16. }

    Of course, manually specifying the attributes for each model seed is cumbersome. Instead, you can use model factories to conveniently generate large amounts of database records. First, review the to learn how to define your factories. Once you have defined your factories, you may use the factory helper function to insert records into your database.

    Calling Additional Seeders

    Within the DatabaseSeeder class, you may use the method to execute additional seed classes. Using the call method allows you to break up your database seeding into multiple files so that no single seeder class becomes overwhelmingly large. Simply pass the name of the seeder class you wish to run:

    1. /**
    2. * Run the database seeds.
    3. *
    4. * @return void
    5. */
    6. public function run()
    7. {
    8. $this->call(UsersTableSeeder::class);
    9. $this->call(PostsTableSeeder::class);
    10. $this->call(CommentsTableSeeder::class);

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

    1. php artisan migrate:refresh --seed