Laravel Factory Helper Command

Laravel Factory Helper Command

The Laravel Factory Helper package by Marcel Pociot helps you generate Laravel test factories from your existing models.

The command that ships with this package helps you get started with testing your application more quickly because it optimistically sets test data with faker in the factories it creates (as opposed to the empty factories generated by make:factory. Moreover, it’s also smart enough to understand model associations and generate the necessary factory code.

As outlined in the readme, given the following model:

Schema::create('users', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name');
    $table->string('username');
    $table->string('email')->unique();
    $table->string('password', 60);
    $table->integer('company_id');
    $table->rememberToken();
    $table->timestamps();
});

class User extends Model {
    public function company()
    {
        return $this->belongsTo(Company::class);
    }
}

This package will produce the following factory:

$factory->define(App\User::class, function (Faker\Generator $faker) {
    return [
        'name' => $faker->name,
        'username' => $faker->userName,
        'email' => $faker->safeEmail,
        'password' => bcrypt($faker->password),
        'company_id' => factory(App\Company::class)->create()->id,
        'remember_token' => Str::random(10),
    ];
});

Related: Going Deeper with Factories Through Factory States

If you want to get a quick demo of how this package supercharges creating test factories in Laravel, check out Jason McCreary’s video where he demos some recent improvements he made to the package:

Since making the video, Jason’s pull request has been merged so everything demoed is available in the latest version of the package.

You can learn more about this package, get full installation instructions, and view the source code on GitHub at mpociot/laravel-test-factory-helper.

Filed in: News

Newsletter

Join 31,000+ others and never miss out on new tips, tutorials, and more.

Laravel News Partners

Laravel Jobs

Senior Laravel Developer
Remote
FPV Exchange
Senior Full-Stack Developer
Remote, USA Only
Givebutter
Full Stack Web Developer
Greenville, TX (or Remote, US)
Innovation First International, Inc.
Senior Software Developer
UK/Germany Only
The Greenhouse People Ltd
Senior PHP Developer
Cary, NC
INE