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 the weekly newsletter and never miss out on new tips, tutorials, and more.

Laravel News Partners

Laravel Jobs

Full Stack or Back-End Developer
Alexandria, VA; Tallahassee, FL; Orlando, FL
Marketing for Change
Full Stack Software Engineer
Atlanta, GA or Remote
Voxie
Laravel/PHP Developer
Chicago, IL
Neon One
Software Engineer, Web Applications
Vaughan, ON, Canada
Blast Motion
Contract Services Software Engineer (Laravel | Vue | Tailwind)
Remote
Riverbed Technology
Senior Laravel Developer
Wilmington, NC
GE Software Inc.
Senior Full Stack Developer (PHP | Vue | DDD)
Charleston, SC
MassageBook