top of page

laravel(part 4->inserting fake data in DB)

  • Writer: sondip poul singh
    sondip poul singh
  • Jan 13, 2019
  • 1 min read

After making a successful connection in the database we want to put some fake data there. To do so we should use the factory of database(database->factory->UserFactory).

There is a default factory like this:

$factory->define(App\User::class, function (Faker $faker) { return [ 'name' => $faker->name, 'email' => $faker->unique()->safeEmail, 'email_verified_at' => now(), 'password' => '$2y$10$TKh8H1.PfQx37YgCzwiKb.KjNyWgaHb9cbcoQgdIVFlYg7B77UdFm', // secret 'remember_token' => str_random(10), ];

like this we can make our own factory.As example:

$factory->define(App\info::class, function (Faker $faker) { return [ 'name' => $faker->name, ]; });

here we write our model name(info) and in the return we write name which is a column of our infos table. And $faker->name puts fake names in the db.

#https://github.com/fzaninotto/Faker

now for sending those fake data to the database we use seeders(database->seeds). We can create a seeder names like InfoSeeder by writing

php artisan make:seeder InfoSeeder

now open the Infoseeder and write:

public function run() { factory(App\info::class,5)->create(); }

this means that we want to use the info factory created earlier and insert 5 fake data there.

finally in DatabaseSeeder.php write the name of the seeder like this:

public function run() { // $this->call(UsersTableSeeder::class); $this->call(InfoSeeder::class); }

Finally write the following to insert data:

php artisan db:seed

Thats all.Awesome!!!

});

Comments


bottom of page