Laravel 5 database seeder example with insert sample user data

Laravel 5 database seeder example with insert sample user data

In this tutorial, I will let you know what is database seeder, what is the use of database seeder and how to generate seeder file with migrations in Laravel 5.

In this example, I will seed some test/dummy data into users table that will not created by any users.

For testing any applications where you will need different user's credentials to test all the scenarios, then you can populate the data by using seed functionality provided by Laravel.

You can generate the seeder class by running following command :

php artisan make:seeder UsersTableSeeder

Once above command will be executed successfully then you will get "UsersTableSeeder" class in database/seeds directory, All the seeders class generated with artisan command will be place in the database/seeds directory.

There will be only one method in seeder class by default :run.

Within the run method, I will write the insert query to load some user data into users table.

Ok, let's open the "UsersTableSeeder.php" file and add the following line of code to insert user data :

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

The above code will insert one record at a time, If you need to insert in bulk then put the code into a loop.

Now run the following command to seed the data :

php artisan db:seed --class=UsersTableSeeder

When you run the artisan command with db:seed option without specifying any class, then this will run the DatabaseSeeder class.

You can break seeders into multiple files and call them in default "DatabaseSeeder" class by using call method. call method is used to call additional seed class.

  1. <?php
  2. use Illuminate\Database\Seeder;
  3. class DatabaseSeeder extends Seeder
  4. {
  5. /**
  6. * Run the database seeds.
  7. *
  8. * @return void
  9. */
  10. public function run()
  11. {
  12. $this->call(UsersTableSeeder::class);
  13. }
  14. }

Now you can run following command:

php artisan db:seed

Phone: (+91) 8800417876
Noida, 201301
ataşehir escort maltepe escort bostancı escort kadıköy escort maltepe escort ataşehir escort kurtköy escort kartal escort pendik escort ataşehir escort
şişli escort
pendik escort
izmir escort izmir escort izmir escort izmir escort denizli escort antalya escort antalya escort antalya escort izmir escort izmir escort izmir escort izmir escort izmir escort