Laravel 4 Database Seeding with Faker

Database seeding can be a pain to perform and end up very clumsy. Seeding is a process required in the majority of web applications – either for stress testing or just to generate a reasonable sample of test data during testing. Laravel 4 already has database seeding and migrations built in, which of course is great. However, the functionality to generate the actual sample data is lacking. Enter Faker – a package, available via composer. The author describes this better than I can:

Faker is a PHP library that generates fake data for you. Whether you need to bootstrap your database, create good-looking XML documents, fill-in your persistence to stress test it, or anonymize data taken from a production service, Faker is for you.

What follows assumes you have a clean install Laravel 4. Lets begin. Add Faker into your composer.json file under the “require” key, below Laravel:

"require": {
   "laravel/framework": "4.0.*",
    "fzaninotto/faker": "1.2.*@dev"
},

Now run a composer update and composer dump-autoload. Faker is now ready to use with our Laravel 4 application.

Create a sample migration using the excellent Laravel 4 Artisan command line that will create a migration to create a test table, called “person”. From the console run:

php artisan migrate:make create_person_table

Hop over to /app/database/migrations and notice a new file has been automatically created, titled in the: “YYYY_MM_DD_HHMMSS_create_person_table.php” format. Open this file and notice how I have added extra code into the “up()” function – this will create our table and columns:

use Illuminate\Database\Migrations\Migration;

class CreatePersonTable extends Migration {

	public function up()
	{
		Schema::create('person', function($table)
		{
		    $table->increments('id');
		    $table->string('name', 250);
		    $table->string('email');
		    $table->text('description');
		    $table->string('country');
		    $table->string('address');
		    $table->string('postcode');
		    $table->string('telephone');
		    $table->string('code');
		    $table->timestamps();
		});
	}

	public function down()
	{
		Schema::drop('person');
	}
}

Now run the following from the console to create the table:

php artisan migrate

We now have an empty table with several columns. Our current goal only require a single model, as we are doing all the work via the Artisan command line.

Now create the a new PHP file at /app/models/Person.php and enter in the following:

class Person extends Eloquent {
  protected $table = 'person';
}

Our setup is now ready to take advantage of Laravel’s Database Seeding feature – we’ll use a separate seeding class to insert our test data. Head over to the /app/database/seeds/ folder and notice Laravel 4 has a sample class, “DatabaseSeeder.php” that we’ll take advantage of – you can of course create your own.

Paste in the following into DatabaseSeeder.php:

class DatabaseSeeder extends Seeder {

	public function run()
	{
		Eloquent::unguard();
		$this->call('PersonTableSeeder');
	}

}

class PersonTableSeeder extends Seeder {

    public function run()
    {
    	$count = 75;

    	$this->command->info('Deleting existing Person table ...');
    	DB::table('person')->delete();

    	$faker = Faker\Factory::create('en_GB');

    	$faker->addProvider(new Faker\Provider\en_GB\Address($faker));
    	$faker->addProvider(new Faker\Provider\en_GB\Internet($faker));
    	$faker->addProvider(new Faker\Provider\Uuid($faker));

        $this->command->info('Inserting '.$count.' sample records using Faker ...');
        // $faker->seed(1234);

        for( $x=0 ; $x<$count; $x++ )
    	{
    		Person::create(array(
    			'name' => $faker->name,
    			'email' => $faker->companyEmail,
    			'description' => '<p>'.  implode('</p><p>', $faker->paragraphs(5)) .'</p>',
    			'country' => $faker->country,
    			'address' => $faker->address,
    			'postcode' => $faker->postcode,
    			'telephone' => $faker->phoneNumber,
    			'code' => $faker->uuid
    		));
    	}

    	$this->command->info('Person table seeded using Faker ...');
    }

}

This code simply utilises Faker to insert our sample data – 75 records. The file also outputs several messages before and after seeding, as there is a slight delay for larger inserts. The above represents a basic use of PHP Faker, but there is a lot of functionality to use if required. For instance, Faker allows us to use our own data providers to insert even more customised data. This is achieved using the addProvider function – 3 built in providers are demonstrated for the current article – see lines 26, 26, 27. The code is very simplist and needs no explanation – we are simply making use of Faker, within a loop to insert rows into our database.

For some needs, it may be desirable to create a seed and to ensure we generate the same data each time the migration is ran. To achieve this, un comment out line 32 (highlighted).

To insert the actual test data return to the command line and run:

php artisan db:seed

When the command has run the following output is observed on the console:

laravel 4 database seeding artisan

Now take a look at your database browser to see 75 freshly inserted records!

That’s it!

Published by

Rob Allport

Web Developer based in Stoke-on-Trent Staffordshire Google+ - Twitter

6 thoughts on “Laravel 4 Database Seeding with Faker”

  1. Whilst this is a good article it’s pointless. I can just export data from an existing site as a SQL dump and import it instantly – wallah, loads of sample data and no messing with external composer packages. If you look at this composer package, faker, it is huge and so puts a huge drain on your spication speed.

    1. @Larval guru

      Assuming that everything you build has the same exact same database, then yeah.

      The size of the package is not relevant, you would only ever use it in development. Never production.

  2. @Larval guru

    Your method is fine if you have an existing database. If you are building an application from scratch Faker provides an excellent way to quickly create fake seed data. Furthermore, you should only include this as a development dependency (through composer), so you wouldn’t even require the package in your production app.

    Regards,
    Chris

  3. This looks really cool- thanks for sharing. Following now so we’ll see how it goes. @LaravalGuru – if you are working on an existing site, yeah -but in my case and likely for many others, it is ideal for quickly stubbing out the data for a site that has no pre-existing data so you can test that different functionality works (record pagination for example).

  4. Thanks for introducing me to the database seeding. I am new in IT field and learning PHP, Html and Database. I hope your posts will help me a lot.

Leave a Reply

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