PHPackages                             directorytree/dummy - 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. [Utility &amp; Helpers](/categories/utility)
4. /
5. directorytree/dummy

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

directorytree/dummy
===================

v2.0.1(1mo ago)439.9k↑31.1%MITPHPCI passing

Since Dec 15Pushed 1mo ago1 watchersCompare

[ Source](https://github.com/DirectoryTree/Dummy)[ Packagist](https://packagist.org/packages/directorytree/dummy)[ RSS](/packages/directorytree-dummy/feed)WikiDiscussions master Synced 2d ago

READMEChangelog (10)Dependencies (28)Versions (20)Used By (0)

[![](https://github.com/DirectoryTree/Dummy/raw/master/art/logo.svg)](https://github.com/DirectoryTree/Dummy/blob/master/art/logo.svg)

Generate PHP class instances populated with fake dummy data using [Faker](https://github.com/FakerPHP/Faker)

[![](https://camo.githubusercontent.com/d2a13234bb5cb31c8ef78d496e9bc9b0058ad817dafee4f39a9f89fe69509862/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f6469726563746f7279747265652f64756d6d792f72756e2d74657374732e796d6c3f6272616e63683d6d6173746572267374796c653d666c61742d737175617265)](https://github.com/directorytree/dummy/actions)[![](https://camo.githubusercontent.com/cbb6e4604084e1233d3906745fb58f8bfaaa7f1cb4c0361b2f4786dc9d8ad0e7/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6469726563746f7279747265652f64756d6d792e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/directorytree/dummy)[![](https://camo.githubusercontent.com/2a7b16dad5691f17fff13e2afc5e2f49fd8936988c96995b87782219ca61e48a/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6469726563746f7279747265652f64756d6d792e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/directorytree/dummy)[![](https://camo.githubusercontent.com/de78b9d1421fdfd0e874a2796e63242d0e56dc17b4091768798ba954c1ee74a6/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f6469726563746f7279747265652f64756d6d792e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/directorytree/dummy)

---

Index
-----

[](#index)

- [Requirements](#requirements)
- [Installation](#installation)
- [Upgrading](#upgrading)
- [Introduction](#introduction)
- [Setup](#setup)
    - [HasDummyFactory Trait](#hasdummyfactory-trait)
    - [Class Factory](#class-factory)
- [Usage](#usage)
    - [Factory States](#factory-states)
    - [Eloquent Attributes](#eloquent-attributes)
    - [Factory Callbacks](#factory-callbacks)
    - [Factory Sequences](#factory-sequences)
    - [Factory Collections](#factory-collections)
    - [Factory Macros](#factory-macros)
    - [IDE Type Inference](#ide-type-inference)

Requirements
------------

[](#requirements)

- PHP &gt;= 8.0

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

[](#installation)

You can install the package via composer:

```
composer require directorytree/dummy --dev
```

Upgrading
---------

[](#upgrading)

### From v1 to v2

[](#from-v1-to-v2)

Dummy v2 renames the trait API so it is explicitly Dummy-owned and does not reserve the common `factory()` method name on your classes.

1. Replace `DirectoryTree\Dummy\HasFactory` with `DirectoryTree\Dummy\HasDummyFactory`.
2. Replace `use HasFactory;` with `use HasDummyFactory;`.
3. Replace `YourClass::factory()` calls with `YourClass::dummy()`.
4. Rename `toFactoryInstance` to `toDummyInstance`.
5. Rename `getFactoryDefinition` to `getDummyDefinition`.
6. Change the `toDummyInstance` argument from `array` to `DirectoryTree\Dummy\DummyData`.

Before:

```
use DirectoryTree\Dummy\HasFactory;

class Reservation
{
    use HasFactory;

    protected static function toFactoryInstance(array $attributes): static
    {
        return new static(
            $attributes['name'],
            $attributes['email'],
        );
    }
}

$reservation = Reservation::factory()->make();
```

After:

```
use DirectoryTree\Dummy\DummyData;
use DirectoryTree\Dummy\HasDummyFactory;

class Reservation
{
    use HasDummyFactory;

    protected static function toDummyInstance(DummyData $attributes): static
    {
        return new static(
            $attributes['name'],
            $attributes['email'],
        );
    }
}

$reservation = Reservation::dummy()->make();
```

If your constructor or factory method needs a plain array, call `all()`:

```
protected static function toDummyInstance(DummyData $attributes): static
{
    return new static($attributes->all());
}
```

You can also replace manual array access with helper methods where useful:

```
$attributes->get('profile.name');
$attributes->filled('email');
$attributes->boolean('active');
$attributes->integer('visits');
$attributes->enum('status', Status::class);
$attributes->enums('roles', Role::class);
$attributes->only(['name', 'email']);
$attributes->except('password');
```

State callbacks, attribute closures, `raw()`, and custom `Factory::generate(array $attributes)` methods continue to receive plain arrays.

Introduction
------------

[](#introduction)

Consider you have a class representing a restaurant reservation:

```
namespace App\Data;

class Reservation
{
    public function __construct(
        public string $name,
        public string $email,
        public DateTime $date,
    ) {}
}
```

To make dummy instances of this class during testing, you have to manually populate it with dummy data.

This can quickly get out of hand as your class grows, and you may find yourself writing the same dummy data generation code over and over again.

Dummy provides you with a simple way to generate dummy instances of your classes using a simple API:

```
// Generate one instance:
$reservation = Reservation::dummy()->make();

// Generate multiple instances:
$collection = Reservation::dummy()->count(5)->make();
```

Setup
-----

[](#setup)

Dummy provides you two different ways to generate classes with dummy data.

### HasDummyFactory Trait

[](#hasdummyfactory-trait)

The `HasDummyFactory` trait is applied directly to the class you would like to generate dummy instances of.

To use the `HasDummyFactory` trait, you must implement the `toDummyInstance` and `getDummyDefinition` methods:

```
namespace App\Data;

use DateTime;
use Faker\Generator;
use DirectoryTree\Dummy\DummyData;
use DirectoryTree\Dummy\HasDummyFactory;

/**
 * @use HasDummyFactory
 */
class Reservation
{
    use HasDummyFactory;

    /**
     * Constructor.
     */
    public function __construct(
        public string $name,
        public string $email,
        public DateTime $date,
    ) {}

    /**
     * Define the factory's default state.
     */
    protected static function getDummyDefinition(Generator $faker): array
    {
        return [
            'name' => $faker->name(),
            'email' => $faker->email(),
            'datetime' => $faker->dateTime(),
        ];
    }

    /**
     * Create a new instance of the class using the factory definition.
     */
    protected static function toDummyInstance(DummyData $attributes): static
    {
        return new static(
            $attributes['name'],
            $attributes['email'],
            $attributes['datetime'],
        );
    }
}
```

The `$attributes` argument passed into `toDummyInstance` is a `DirectoryTree\Dummy\DummyData` instance. It supports array access and common data helpers, such as `get`, `has`, `filled`, `notFilled`, `boolean`, `integer`, `enum`, `enums`, `only`, `except`, `collect`, and `all`.

Once implemented, you may call the `Reservation::dummy()` method to create a new dummy factory:

```
$factory = Reservation::dummy();
```

#### Dynamic State Methods

[](#dynamic-state-methods)

The `HasDummyFactory` trait supports defining dynamic state methods. You can define state methods in your class using the format `get{StateName}State` and call them dynamically on the factory:

```
namespace App\Data;

use DateTime;
use Faker\Generator;
use DirectoryTree\Dummy\DummyData;
use DirectoryTree\Dummy\HasDummyFactory;

/**
 * @use HasDummyFactory
 */
class Reservation
{
    use HasDummyFactory;

    public function __construct(
        public string $name,
        public string $email,
        public DateTime $datetime,
        public string $status = 'pending',
        public string $type = 'standard',
    ) {}

    // Dynamic state methods...

    public static function getConfirmedState(): array
    {
        return ['status' => 'confirmed'];
    }

    public static function getPremiumState(): array
    {
        return [
            'type' => 'premium',
            'status' => 'confirmed',
        ];
    }

    public static function getCancelledState(): array
    {
        return ['status' => 'cancelled'];
    }

    protected static function toDummyInstance(DummyData $attributes): self
    {
        return new static(
            $attributes['name'],
            $attributes['email'],
            $attributes['datetime'],
            $attributes['status'] ?? 'pending',
            $attributes['type'] ?? 'standard',
        );
    }

    protected static function getDummyDefinition(Generator $faker): array
    {
        return [
            'name' => $faker->name(),
            'email' => $faker->email(),
            'datetime' => $faker->dateTime(),
        ];
    }
}
```

You can then use these state methods dynamically:

```
// Create a confirmed reservation
$confirmed = Reservation::dummy()->confirmed()->make();

// Create a premium reservation
$premium = Reservation::dummy()->premium()->make();

// Chain multiple states
$premiumCancelled = Reservation::dummy()->premium()->cancelled()->make();
```

### Class Factory

[](#class-factory)

If you need more control over the dummy data generation process, you may use the `Factory` class.

The `Factory` class is used to generate dummy instances of a class using a separate factory class definition.

To use the `Factory` class, you must extend it with your own and override the `definition` and `generate` methods:

```
namespace App\Factories;

use App\Data\Reservation;
use DirectoryTree\Dummy\Factory;

/**
 * @extends Factory
 */
class ReservationFactory extends Factory
{
    /**
     * Define the factory's default state.
     */
    protected function definition(): array
    {
        return [
            'name' => $this->faker->name(),
            'email' => $this->faker->email(),
            'datetime' => $this->faker->dateTime(),
        ];
    }

    /**
     * Generate a new instance of the class.
     */
    protected function generate(array $attributes): Reservation
    {
        return new Reservation(
            $attributes['name'],
            $attributes['email'],
            $attributes['datetime'],
        );
    }
}
```

Usage
-----

[](#usage)

Once you've defined a factory, you can generate dummy instances of your class using the `make` method:

```
// Using the trait:
$reservation = Reservation::dummy()->make();

// Using the factory class:
$reservation = ReservationFactory::new()->make();
```

To add or override attributes in your definition, you may pass an array of attributes to the `make` method:

```
$reservation = Reservation::dummy()->make([
    'name' => 'John Doe',
]);
```

To generate multiple instances of the class, you may use the `count` method:

> This will return an `Illuminate\Support\Collection` instance containing the generated classes.

```
$collection = Reservation::dummy()->count(5)->make();
```

If you have a counted factory but need one instance, use `makeOne`:

```
$reservation = Reservation::dummy()->count(5)->makeOne();
```

To make several instances with a different state record for each one, use `makeMany`:

```
$collection = Reservation::dummy()->makeMany([
    ['name' => 'Taylor Otwell'],
    ['name' => 'Nuno Maduro'],
]);
```

You may also defer generation by creating a lazy callback:

```
$makeReservation = Reservation::dummy()->lazy([
    'name' => 'John Doe',
]);

$reservation = $makeReservation();
```

### Factory States

[](#factory-states)

State manipulation methods allow you to define discrete modifications that can be applied to your dummy factories in any combination.

For example, your `App\Factories\Reservation` factory might contain a `tomorrow`state method that modifies one of its default attribute values:

```
class ReservationFactory extends Factory
{
    // ...

    /**
     * Indicate that the reservation is for tomorrow.
     */
    public function tomorrow(): Factory
    {
        return $this->state(function (array $attributes) {
            return ['datetime' => new DateTime('tomorrow')];
        });
    }
}
```

You may prepend a state when you need it evaluated before the factory's existing states:

```
$reservation = Reservation::dummy()
    ->tomorrow()
    ->prependState([
        'name' => 'Early State',
    ])
    ->make();
```

### Eloquent Attributes

[](#eloquent-attributes)

When Laravel's Eloquent is installed, Dummy will expand Eloquent model instances and factories into model keys:

```
use App\Models\Company;
use App\Models\User;

$reservation = Reservation::dummy()->make([
    'company_id' => Company::factory(),
    'user_id' => User::factory()->create(),
]);
```

This also works for values returned from attribute closures, so dependent attributes can use previously expanded keys:

```
$reservation = Reservation::dummy()->make([
    'company_id' => Company::factory(),
    'user_id' => fn (array $attributes) => User::factory([
        'company_id' => $attributes['company_id'],
    ]),
]);
```

### Factory Callbacks

[](#factory-callbacks)

Factory callbacks are registered using the `afterMaking` method and allow you to perform additional tasks after making or creating a class. You should register these callbacks by defining a `configure` method on your factory class. This method will be automatically called when the factory is instantiated:

```
class ReservationFactory extends Factory
{
    // ...

    /**
     * Configure the dummy factory.
     */
    protected function configure(): static
    {
        return $this->afterMaking(function (Reservation $reservation) {
            // ...
        });
    }
}
```

You may remove configured `afterMaking` callbacks for a single factory chain with `withoutAfterMaking`:

```
$reservation = ReservationFactory::new()
    ->withoutAfterMaking()
    ->make();
```

### Factory Sequences

[](#factory-sequences)

Sometimes you may wish to alternate the value of a given attribute for each generated class.

You may accomplish this by defining a state transformation as a `sequence`:

```
Reservation::dummy()
    ->count(3)
    ->sequence(
        ['datetime' => new Datetime('tomorrow')],
        ['datetime' => new Datetime('next week')],
        ['datetime' => new Datetime('next month')],
    )
    ->make();
```

### Factory Collections

[](#factory-collections)

By default, when making more than one dummy class, an instance of `Illuminate\Support\Collection` will be returned.

If you need to customize the collection of classes generated by a factory, you may override the `collect` method:

```
class ReservationFactory extends Factory
{
    // ...

    /**
     * Create a new collection of classes.
     */
    public function collect(array $instances = []): ReservationCollection
    {
        return new ReservationCollection($instances);
    }
}
```

### Factory Macros

[](#factory-macros)

Factories are macroable, allowing you to register reusable factory helpers:

```
use DirectoryTree\Dummy\Factory;

Factory::macro('named', function (string $name) {
    return $this->state([
        'name' => $name,
    ]);
});

$reservation = Reservation::dummy()->named('John Doe')->make();
```

### IDE Type Inference

[](#ide-type-inference)

Dummy includes generic PHPDoc annotations so static analysis tools and IDEs can infer factory return types.

When using the `HasDummyFactory` trait, add an `@use` annotation to your class:

```
/**
 * @use HasDummyFactory
 */
class Reservation
{
    use HasDummyFactory;

    // ...
}
```

When using a dedicated factory class, add an `@extends` annotation:

```
/**
 * @extends Factory
 */
class ReservationFactory extends Factory
{
    // ...
}
```

These annotations allow tools to infer that `Reservation::dummy()->makeOne()` and `ReservationFactory::new()->makeOne()` return a `Reservation` instance.

###  Health Score

49

—

FairBetter than 94% of packages

Maintenance92

Actively maintained with recent releases

Popularity35

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity47

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 95.6% 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 ~43 days

Recently: every ~0 days

Total

13

Last Release

39d ago

Major Versions

v1.6.1 → v2.0.x-dev2026-05-24

### Community

Maintainers

![](https://www.gravatar.com/avatar/c6dd082636ff8a08df8dfdcd622ea242374d1d76dd33bceec5a6cd3ae26dc24f?d=identicon)[stevebauman](/maintainers/stevebauman)

---

Top Contributors

[![stevebauman](https://avatars.githubusercontent.com/u/6421846?v=4)](https://github.com/stevebauman "stevebauman (86 commits)")[![Copilot](https://avatars.githubusercontent.com/in/1143301?v=4)](https://github.com/Copilot "Copilot (4 commits)")

###  Code Quality

TestsPest

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/directorytree-dummy/health.svg)

```
[![Health](https://phpackages.com/badges/directorytree-dummy/health.svg)](https://phpackages.com/packages/directorytree-dummy)
```

###  Alternatives

[illuminate/support

The Illuminate Support package.

630113.0M41.3k](/packages/illuminate-support)[illuminate/events

The Illuminate Events package.

13557.0M2.1k](/packages/illuminate-events)[illuminate/config

The Illuminate Config package.

10944.5M2.5k](/packages/illuminate-config)[illuminate/pagination

The Illuminate Pagination package.

12234.1M1.0k](/packages/illuminate-pagination)[illuminate/session

The Illuminate Session package.

9939.3M849](/packages/illuminate-session)[illuminate/broadcasting

The Illuminate Broadcasting package.

7127.2M208](/packages/illuminate-broadcasting)

PHPackages © 2026

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