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
Laravel News Partners

Laravel Jobs

Backend Software Engineer (PHP Developer)
Austin TX, Bonita Springs FL
Certified eSupport Corp
Laravel Developer
Glendale, CA (COVID Remote)
Jogg, Inc
Senior PHP Engineer
Remote, USA Only
Kittyhawk
Full Stack Engineer
Remote
Shelterluv
Kickass LaraDev!
Remote
Megaverse

Newsletter

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