Automatically Create Model Factories


March 29th, 2016


Laravel Test Factory Generator is a new package by Marcel Pociot that generates model factories from your existing models and database structure.

Once installed it gives you a new Artisan command to generate the model factories:

php artisan test-factory-helper:generate

This command will then look through all your models, create test factories, and save them in your database/factories/ModelFactory.php file.

To prevent overwriting any of your existing factories, the command will append new ones and not modify any existing. It does include a --reset flag that will rewrite the entire ModelFactory file.

As an example if you have the following migration:

Schema::create('users', function (Blueprint $table) {
    $table->string('password', 60);

Once you run the command this will be appended to your ModelFactory.php file:

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

You can find more information on Github.

Filed in:

Eric L. Barnes

Eric is the creator of Laravel News and has been covering Laravel since 2012.