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:

    A seeder class only contains one method by default: run. This method is called when the db:seed is executed. Within the run method, you may insert data into your database however you wish. You may use the query builder to manually insert data or you may use .

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

    {tip} You may type-hint any dependencies you need within the run method's signature. They will automatically be resolved via the Laravel service container.

    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.

    For example, let's create 50 users and attach a relationship to each user:

    Calling Additional Seeders

    1. /**
    2. * Run the database seeds.
    3. *
    4. */
    5. public function run()
    6. {
    7. $this->call([
    8. UsersTableSeeder::class,
    9. PostsTableSeeder::class,
    10. CommentsTableSeeder::class,
    11. ]);
    12. }

    Once you have written your seeder, you may need to regenerate Composer's autoloader using the dump-autoload command:

    Now you may use the db:seed Artisan command to seed your database. By default, the db:seed command runs the DatabaseSeeder class, which may be used to call other seed classes. However, you may use the —class option to specify a specific seeder class to run individually:

    1. php artisan db:seed
    2. php artisan db:seed --class=UsersTableSeeder

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

    Forcing Seeders To Run In Production