PHPackages                             fbarrento/data-factory - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Testing &amp; Quality](/categories/testing)
4. /
5. fbarrento/data-factory

ActiveLibrary[Testing &amp; Quality](/categories/testing)

fbarrento/data-factory
======================

Test data factory for PHP

v1.1.0(7mo ago)71.4k↑1206.7%1[1 issues](https://github.com/fbarrento/data-factory/issues)1MITPHPPHP ^8.2.0CI passing

Since Nov 11Pushed 7mo agoCompare

[ Source](https://github.com/fbarrento/data-factory)[ Packagist](https://packagist.org/packages/fbarrento/data-factory)[ GitHub Sponsors](https://github.com/fbarrento)[ RSS](/packages/fbarrento-data-factory/feed)WikiDiscussions main Synced today

READMEChangelog (2)Dependencies (8)Versions (5)Used By (1)

PHP Data Factories
==================

[](#php-data-factories)

 [![GitHub Workflow Status](https://github.com/fbarrento/data-factory/actions/workflows/tests.yml/badge.svg)](https://github.com/fbarrento/data-factory/actions) [![Total Downloads](https://camo.githubusercontent.com/11f42634cdc13ebec2126b58b9a0767549e4701cee1e47a253ce1a45aaa3570d/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6662617272656e746f2f646174612d666163746f7279)](https://packagist.org/packages/fbarrento/data-factory) [![Latest Version](https://camo.githubusercontent.com/c74b75a320ca1ac2736e19167d8a45870fc466485c0f019305bd85a3cecd8165/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6662617272656e746f2f646174612d666163746f7279)](https://packagist.org/packages/fbarrento/data-factory) [![License](https://camo.githubusercontent.com/d52edaafa49e618e60d39679ead6fe32a480e60b9c31dbd9a5baadfc39fe7ded/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f6662617272656e746f2f646174612d666163746f7279)](https://packagist.org/packages/fbarrento/data-factory)

---

**The modern test data factory for PEST.** Write cleaner, more maintainable PHP tests with expressive factories.

Inspired by Laravel's Eloquent factories, Data Factory brings the same elegant API to any PHP project—no framework required.

✨ Features
----------

[](#-features)

- ✅ **Write DRY test code** - Define test data once, reuse everywhere
- ✅ **Readable test assertions** - Clear intent with named states like `->succeeded()`
- ✅ **Easy complex objects** - Create nested graphs without boilerplate
- ✅ **Built with PEST in mind** - Works with any PHP testing framework, optimized for PEST
- ✅ **Framework-agnostic** - Works with any PHP class, not tied to Eloquent
- ✅ **Type-safe factories** - Modern type hints with 100% type coverage
- ✅ **Faker integration** - Realistic test data out of the box

📋 Requirements
--------------

[](#-requirements)

- PHP 8.2 or higher
- Composer

> Fully tested on PHP 8.2, 8.3, 8.4 across Windows, Linux, and macOS

Installation
------------

[](#installation)

Install via [Composer](https://getcomposer.org):

```
composer require fbarrento/data-factory --dev
```

Why Use Data Factories for Testing?
-----------------------------------

[](#why-use-data-factories-for-testing)

**The Problem:** Test setup code is repetitive, hard to maintain, and clutters your test files.

```
// ❌ Without factories - repetitive and brittle
it('processes deployment', function () {
    $deployment = [
        'id' => '123e4567-e89b-12d3-a456-426614174000',
        'status' => 'deployment.succeeded',
        'branch_name' => 'main',
        'commit_hash' => 'a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9t0',
        'commit_message' => 'Deploy feature X to production',
        'failure_reason' => null,
        'php_major_version' => '8.4',
        'uses_octane' => true,
        'started_at' => '2024-01-15 10:00:00',
        'finished_at' => '2024-01-15 10:05:00',
    ];

    // Your actual test logic here...
});
```

```
// ✅ With factories - clean and focused
it('processes deployment', function () {
    $deployment = Deployment::factory()->succeeded()->make();

    // Your actual test logic here - clear and focused!
});
```

**The Benefits:**

- **DRY (Don't Repeat Yourself)** - Define test data once, reuse across all tests
- **Maintainability** - Change data structure in one place, not hundreds of tests
- **Readability** - `->succeeded()` is clearer than 10 lines of setup
- **Flexibility** - Easy to test edge cases with different states
- **Focus** - Spend time testing behavior, not setting up data

Quick Start
-----------

[](#quick-start)

```
// tests/Factories/DeploymentFactory.php
use FBarrento\DataFactory\Factory;

class DeploymentFactory extends Factory
{
    protected function definition(): array
    {
        return [
            'id' => $this->fake->uuid(),
            'status' => 'pending',
            'branch_name' => 'main',
            'commit_hash' => $this->fake->sha1(),
        ];
    }

    public function succeeded(): static
    {
        return $this->state(['status' => 'deployment.succeeded']);
    }
}

// tests/Feature/DeploymentTest.php
it('handles successful deployments', function () {
    $deployment = Deployment::factory()->succeeded()->make();

    expect($deployment->status)->toBe('deployment.succeeded');
});

it('creates multiple test deployments', function () {
    $deployments = Deployment::factory()->count(5)->make();

    expect($deployments)->toHaveCount(5);
});
```

Documentation
-------------

[](#documentation)

- **[Getting Started](docs/index.md)** - Overview and feature list
- **[Installation](docs/installation.md)** - Install and setup
- **[Basic Usage](docs/basic-usage.md)** - Create your first factory
- **[Faker Integration](docs/faker.md)** - Generate realistic fake data
- **[States](docs/states.md)** - Define reusable variations
- **[Sequences](docs/sequences.md)** - Cycle through values
- **[Nested Factories](docs/nested-factories.md)** - Build complex object graphs
- **[Array Factories](docs/array-factories.md)** - Generate arrays for JSON/API responses
- **[Class Integration](docs/model-integration.md)** - Integrate factories with your classes using HasDataFactory trait
- **[Advanced Examples](docs/advanced-examples.md)** - Real-world Laravel Cloud API examples
- **[Testing](docs/testing.md)** - Use factories in PEST tests

Roadmap
-------

[](#roadmap)

Features under consideration for future releases:

- 🎯 **`raw()` method** - Return attribute arrays without instantiating objects, useful for testing raw data or API payloads ```
    $attributes = Vehicle::factory()->raw(); // Returns ['make' => '...', 'model' => '...']
    ```
- 🪝 **`afterMaking()` callbacks** - Post-processing hooks for generated data, enabling validation or side effects ```
    Vehicle::factory()
        ->afterMaking(fn($vehicle) => logger()->info('Made vehicle', ['id' => $vehicle->id]))
        ->make();
    ```
- 🗂️ **Export to JSON** - Save datasets as JSON fixtures for testing or seeding ```
    Vehicle::factory()->count(1000)->toJson('fixtures/vehicles.json');
    ```
- 📦 **Export to Arrays** - Transform objects to nested array structures ```
    $array = Customer::factory()->count(100)->toArray();
    ```
- ⚡ **Streaming/Chunking** - Process large datasets (100k+ records) without memory issues ```
    Vehicle::factory()->count(200000)->chunk(1000)->toJson('fixtures/vehicles.json');
    ```
- 🚨 **Exception Handling** - Custom exceptions with helpful error messages for configuration and validation errors

Have ideas for other features? [Open an issue](https://github.com/fbarrento/data-factory/issues) or submit a PR!

Contributing
------------

[](#contributing)

We welcome contributions! Data Factory is built with high quality standards:

- ✅ 100% test coverage
- ✅ 100% type coverage
- ✅ PHPStan level 9
- ✅ Modern PHP 8.2+ patterns

**Quick Start for Contributors:**

```
# Run all quality checks
composer test

# Format code
composer lint

# Run tests with coverage
composer test:unit
```

For detailed contributing guidelines, development setup, and code standards, see [CONTRIBUTING.md](CONTRIBUTING.md).

References
----------

[](#references)

- [Stop Writing Arrays in Your Tests: Laravel Factories for Data Objects](https://barrento.test/blog/stop-writing-arrays-in-your-tests-laravel-factories-for-data-objects) - The article that inspired this package

License
-------

[](#license)

Data Factory is open-sourced software licensed under the [MIT license](LICENSE.md).

###  Health Score

39

—

LowBetter than 84% of packages

Maintenance60

Regular maintenance activity

Popularity26

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity51

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~0 days

Total

2

Last Release

234d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/55e5f328060e43ab78736d6d3b53dd144fe8f175774d77d2bf86985cb8451b21?d=identicon)[fbarrento](/maintainers/fbarrento)

---

Top Contributors

[![fbarrento](https://avatars.githubusercontent.com/u/8377450?v=4)](https://github.com/fbarrento "fbarrento (38 commits)")

---

Tags

phptestingfixturesdata-factory

###  Code Quality

TestsPest

Static AnalysisPHPStan, Rector

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

![Health badge](/badges/fbarrento-data-factory/health.svg)

```
[![Health](https://phpackages.com/badges/fbarrento-data-factory/health.svg)](https://phpackages.com/packages/fbarrento-data-factory)
```

###  Alternatives

[marvinrabe/laravel-graphql-test

Provides you with a simple GraphQL testing trait.

57378.9k](/packages/marvinrabe-laravel-graphql-test)[quizlet/hammock

Hammock is a stand-alone mocking library for Hacklang.

27445.5k](/packages/quizlet-hammock)[robiningelbrecht/phpunit-coverage-tools

PHPUnit coverage tools

17143.1k51](/packages/robiningelbrecht-phpunit-coverage-tools)[doppiogancio/mocked-client

A simple way to mock a client

1975.9k5](/packages/doppiogancio-mocked-client)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
