anonymoussc
Aug 24, 2015 • 1 min read

Creating large amounts of sample data using Faker

Require Laravel 5.1.

Faker package is included by default in require-dev composer.json as of laravel 5.1.

Create the class table seeder (file name format modelNameTableSeeder.php) in /database/seeds/ directory, put the example code bellow in the run() method of the class.

    $faker = \Faker\Factory::create();
    
    Todolist::truncate();
    
    foreach (range(1, 50) as $index) {
        Todolist::create([
            'name'        => $faker->sentence(2),
            'description' => $faker->sentence(4),
        ]);
    }

This will truncate (remove) the table record then it will loop (foreach) to create 50 new record for name field it will contain a sentence with 2 words and descripton field with a sentence of 4 words.

Faker can be useful for many task related to sample data, Faker documentation.

The working example of code snipet above as follow. File located at /database/seeds/ TodolistTableSeeder.php

It need to be called from the database seeder class ( /database/seeds/ DatabaseSeeder.php ) using :

$this->call('TodolistTableSeeder');

Again, an example bellow. File located at /database/seeds/ DatabaseSeeder.php

Rebuild class map, run :

composer dump-autoload

Seeding the database :

php artisan db:seed

The key to good decision making is evaluating the available information - the data - and combining it with your own estimates of pluses and minuses. As an economist, I do this every day. - Emily Oster

Post by: Anonymoussc (@anonymoussc)