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:

1php 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:

1Schema::create('users', function (Blueprint $table) {
2 $table->increments('id');
3 $table->string('name');
4 $table->string('username');
5 $table->string('email')->unique();
6 $table->string('password', 60);
7 $table->rememberToken();
8 $table->timestamps();

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

1$factory->define(App\User::class, function (Faker\Generator $faker) {
2 return [
3 'name' => $faker->name ,
4 'username' => $faker->userName ,
5 'email' => $faker->safeEmail ,
6 'password' => bcrypt($faker->password) ,
7 'remember_token' => str_random(10) ,
8 ];

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.

Laravel News Partners