Class-Based Factories with Laravel Poser


April 10th, 2020


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()

    $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()

    $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) {

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:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.