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

Laravel Senior Developer
Remote, Canada Only
BeMo Academic Consulting
Senior Fullstack Developer / Architect (w/m/d)
Remote / Munich - Germany
envivo.select GmbH
Medior full stack developer (Laravel)
Deventer (or remote) in the Netherlands, Dutch speaking required.
MSML B.V.
Senior Full Stack PHP Developer (Laravel)
Remote
MAPPEN
Senior Laravel Developer
Remote
ACTO