Using Factories with Your Laravel 5 Tests

  • June 25, 2015

Welcome to the incredibly popular Easy Laravel 5 companion blog. To celebrate the new edition's release (updated for Laravel 5.5!) use the discount code easteregg to receive 20% off the book or book/video package! » Buy the book

Laravel 5.1 introduces a great new feature known as a factory. Factories are useful for generating sample data which can then be used in your tests. In this blog post you'll learn how to create factories and use them within your tests.

Laravel 5.1+ applications include an example User model factory (this model is introduced in chapter 5), found in database/factories/ModelFactory.php:

$factory->define(App\User::class, function ($faker) {
    return [
        'name' => $faker->name,
        'email' => $faker->email,
        'password' => str_random(10),
        'remember_token' => str_random(10),

This factory uses the previously introduced Faker package to generate a placeholder name and e-mail address, and additionally uses PHP's str_random() function to generate a random password and password recovery token. Keep in mind you're free to set any column using a static value, although tools such as Faker will save you quite a bit of hassle when you'd like to create a large number of sample records.

Add the following Todolist factory below the factory defined above:

$factory->define(App\Todolist::class, function ($faker) {
    return [
        'name' => 'blah',
        'description' => $faker->name

With the factory created you can then reference it within your tests like so:

$listFactory = factory('App\Todolist')->create();

Executing the factory in conjunction with create() will cause the record to be saved to the database. You could optionally just create an object of type Todolist containing the information found in the factory by instead using make():

$listFactory = factory('App\Todolist')->make();

Perhaps not surprisingly the latter approach will be faster, and so is recommended when there is no need to subsequently retrieve factory-generated data from the database during the course of the test.