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

PHP Data Engineer
Remote (US)
FBS
Software Developer
Remote (US & Canada)
Alley
Backend Software Engineer
Remote (UTC +/- 5)
Smartbnb
Programmer
Remote (Overlap w/ Continental US Time Zones)
Tighten
Senior Backend Engineer
Remote
64 Robots
Senior Laravel Developer
Atlanta, GA
Helium LLC
Full-Stack Developer (JS - Vue.js, PHP - Laravel)
US Remote / Telecommute
TTEC Digital