Laravel Packages / updated: July 19, 2016

Automatically Create Model Factories

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->increments('id');
    $table->string('name');
    $table->string('username');
    $table->string('email')->unique();
    $table->string('password', 60);
    $table->rememberToken();
    $table->timestamps();
});

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.

This appeared first on Laravel News
Laravel News Partners

Newsletter

Join the weekly newsletter and never miss out on new tips, tutorials, and more.