Class-Based Factories with Laravel Poser

Class-Based Factories with Laravel Poser

With Laravel Poser, you can “create class-based model factories in Laravel applications in seconds.” This package works by creating factory classes by hand or using the artisan make:poser command:

namespace Tests\Factories;

use Lukeraymonddowning\Poser\Factory;

class UserFactory extends Factory {}

Here’s a basic example of a test case using a Poser factory class:

/** @test */
public function a_user_can_have_customers()
{
    UserFactory::times(20)
               ->hasAddress()
               ->withCustomers(CustomerFactory::times(20)->withBooks(5))();

    $this->assertCount(20 * 20 * 5, Book::all());
}

Poser is smart enough to figure out that withCustomers() is a reference to a CustomerFactory class, so you could write it as follows instead:

/** @test */
public function user_has_customers()
{
    $user = UserFactory::new()
        ->withCustomers(30)
        ->create();

    $this->assertCount(30, $user->customers);
}

Another highlight is the ability to encapsulate everyday factory tasks:

class CompanyFactory extends Factory
{
    public function withMainUser()
    {
        return $this->afterCreating(function(Company $company) {
            $company->setMainUser(
                UserFactory::new()
                    ->forCompany($company)->create()
            );
        });
    }
}

The poser readme has many thorough examples and details about how to use this package. You can learn more by checking out Poser on GitHub!

Filed in: News / packages

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
Senior PHP Developer
Cary, NC
INE
Backend PHP Developer
Hamburg
ABOUT YOU GmbH
Engineering Director
Vancouver or remote (EST/PST preferred)
Engine Digital