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

    $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: News / packages


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 GmbH
Medior full stack developer (Laravel)
Deventer (or remote) in the Netherlands, Dutch speaking required.
Senior Full Stack PHP Developer (Laravel)
Senior Laravel Developer