Laravel Seeder with Faker Data Factory

We previously discussed about Laravel Seeders. Seeders are awesome with Faker. So what’s Faker ? So, today we’re gonna discuss Laravel Seeder with Faker Data Factory.

Understanding Laravel Seeder with Faker Data

You can insert a set of data by running a single command using Laravel Seeders. But, what if you want hundreds of records of dummy data to be inserted to your system? Well, that’s where Laravel Seeder with Faker Data comes into play.

Let’s Give it a try

Let’s give it a try by Installing a new Laravel copy.

Once the installation is complete, create a table where you want to insert your data. Using Laravel Migrations is the best and the easiest way to create tables in Laravel.  Make sure you create a Laravel Model as well to map the table.

In this case I’m creating a table name companies¬†and its corresponding model is Company.

Once the table and model are created, run the following command to create the factory.

Great! Now, open up database > factories folder and you’ll see your factory is created there.

Larave Factory file

 

Now update it with the following lines of code that defines the Faker data.

use Faker\Generator as Faker;

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

 

Here I’m getting Faker data for company names. Check the Faker repository on Git hub to see all the formatters.

Once this is complete, we need to add this to the DatabaseSeeder.php. Open up DatabaseSeeder.php in the same folder and add the below code.

public function run()
{
     $products = factory(\App\Company::class, 1000)->create();
}

Great! Now, run the below command to run this factory.

php artisan db:seed

Check your table and you’ll see 1000 lines of records has been inserted to your table.

There are many formatters available in the Faker repository.  You can use them according to the data structure you want.

Faker Formatters

 

Let’s say you want some dummy data related to Addresses. the you’ll get thousands of dummy addresses by running a single command. Like that you can get dummy data for Person names, Phone numbers, Colors, and so on.

That’s it! Thanks!

Leave a Reply

Your email address will not be published. Required fields are marked *