How to seed using faker in laravel?

by wilmer.lemke , in category: PHP Frameworks , 21 days ago

How to seed using faker in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by darion , 20 days ago

@wilmer.lemke 

To seed a database using Faker in Laravel, you can follow these steps:

  1. Install Faker package: First, you need to install the Faker package in your Laravel project. You can do this by running the following command in your terminal:


composer require fzaninotto/faker

  1. Create a Seeder: Next, you need to create a new seeder using the Artisan command:


php artisan make:seeder UsersTableSeeder


This command will generate a new seeder class in the database/seeds directory.

  1. Edit the Seeder: Open the seeder file you just created (UsersTableSeeder.php) and use the Faker library to generate fake data for your database table. Here is an example of how you can use Faker to generate fake users:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
use IlluminateDatabaseSeeder;
use FakerFactory as Faker;

class UsersTableSeeder extends Seeder
{
    public function run()
    {
        $faker = Faker::create();

        foreach(range(1, 50) as $index) {
            DB::table('users')->insert([
                'name' => $faker->name,
                'email' => $faker->unique()->safeEmail,
                'password' => bcrypt('password'),
            ]);
        }
    }
}


  1. Run the Seeder: Finally, run the seeder using the following Artisan command:


php artisan db:seed --class=UsersTableSeeder


This will populate your database with fake user data using Faker.


That's it! You have successfully seeded your database using Faker in Laravel.