Creating Fake / Test data in PHP

August 18, 2014 in PHP


Yesterday I was looking around for a way to easily populate a database to test out some of my code. Instead of sitting there for hours punching out tons of random stuff, I decided that there had to be a better way. That's when I ran across Faker.

Faker (on Github) is a PHP library the aims to make creating fake data fro testing purposes super, super easy.

The easiest way to install faker is via composer. Since I'm using Laravel, this is simple because all other dependencies are managed by composer. To install it, simply add it to your composer.json file and run a composer update

"require-dev": {  "fzaninotto/faker": "1.3.*@dev"},

Alright, now that its installed we can use it to begin creating fake data. For this example, lets say you wanted to create some user objects. In this example I'm going to user an Eloquent implementation, but it would be really similar for other ORMs or for your own custom object.

// create a new Faker 
object$faker = Faker\\Factory::create();

// lets make ourselves 25 users
for ($i = 0; $i < 25; $i++){  
    $user = User::create(array(    
        'first_name' => $faker->firstName,    
        'last_name'  => $faker->lastName,    
        'email'      => $faker->email,    
        'password'   => $faker->word  
    ));
}

How neat is that?! We just created an inserted 25 random users into our database without having to come up with one name! I will continue to use faker to test and seed my databases in Laravel apps for a while. I love how simple and easy to use it is.

One final note. Lets say you actually wanted to create your own custom list of names. Thats totally possible with Faker. All of the names are simply arrays of strings located in a Provider file. The provider file for names (en_US locale) is in /src/Faker/Provider/en_US/Person.php. All you gotta do is either edit or override that to add your own names