LaraflareDocsFrameworkPackagesReleases13.x

Docs / Eloquent ORM / Eloquent: Factories

Eloquent: Factories

Introduction

When testing your application or seeding your database, you may need to insert a few records into your database. Instead of manually specifying the value of each column, laraflare allows you to define a set of default attributes for each of your Eloquent models using model factories.

To see an example of how to write a factory, take a look at the database/factories/UserFactory.ts file in your application. This factory is included with all new laraflare applications and contains the following factory definition:

import { Factory, Str, now } from '@laraflare/framework';
import { Hash } from '@laraflare/framework/hashing';
import { User } from '../../app/Models/User';

export class UserFactory extends Factory<User> {
  static override model = User;
  static { Factory.register(this); }

  /**
   * The current password being used by the factory.
   */
  protected static password: string | undefined;

  /**
   * Define the model's default state.
   */
  override async definition(): Promise<Record<string, unknown>> {
    return {
      name: 'Test User',
      email: `${Str.random(10).toLowerCase()}@example.com`,
      email_verified_at: now(),
      password: UserFactory.password ??= await Hash.make('password'),
      remember_token: Str.random(10),
    };
  }

  /**
   * Indicate that the model's email address should be unverified.
   */
  unverified(): this {
    return this.state(() => ({
      email_verified_at: null,
    }));
  }
}

As you can see, in their most basic form, factories are classes that extend laraflare's base factory class and define a definition method. The definition method returns the default set of attribute values that should be applied when creating a model using the factory. It may be async, as above, when a value has to be awaited.

The static model property names the model the factory makes, and Factory.register(this) makes the factory known by its class name, so the model's factory method and the relationship methods described below can find it.

Note

laraflare has no Faker and no fake helper. A factory writes its own values: fixed strings, the Str helpers such as Str.random(10) and Str.uuid(), now() for dates, or a sequence when each model needs a different value.

Defining Model Factories

Generating Factories

To create a factory, execute the make:factory Artisan command:

npx artisan make:factory PostFactory

The new factory class will be placed in your database/factories directory. When the Post model exists (or a model is given with the --model option), the factory names it and registers itself:

import { Factory } from '@laraflare/framework';
import { Post } from '../../app/Models/Post';

export class PostFactory extends Factory<Post> {
  static override model = Post;
  static { Factory.register(this); }

  /**
   * Define the model's default state.
   */
  override definition(): Record<string, unknown> {
    return {
      //
    };
  }
}

Model and Factory Discovery Conventions

Once you have defined your factories, you may use the static factory method provided to your models by the HasFactory mixin in order to instantiate a factory instance for that model.

The HasFactory mixin's factory method will use conventions to determine the proper factory for the model the mixin is applied to. Specifically, the method will look for a registered factory that has a class name matching the model name and is suffixed with Factory. If these conventions do not apply to your particular application or factory, use the static model property on the factory to specify its model; a registered factory is found by its model, whatever its name:

import { Factory } from '@laraflare/framework';
import { Flight } from '../../../app/Models/Flight';

export class AircraftScheduleFactory extends Factory<Flight> {
  static override model = Flight;
  static { Factory.register(this); }

  // ...
}

The model names its factory with a type-only declaration, as npx artisan make:model Flight --factory writes it, so the compiler knows that Flight.factory() is that factory and its own state methods may be called on it:

import { HasFactory, Model } from '@laraflare/framework';
import type { AircraftScheduleFactory } from '../../database/factories/AircraftScheduleFactory';

export class Flight extends HasFactory(Model) {
  /** The model's factory, so Flight.factory() is an AircraftScheduleFactory. */
  declare static useFactory: typeof AircraftScheduleFactory;

  // ...
}

Note

The model imports its factory's type only. The factory imports the model to name it, so a model that imported its factory's class as a value would be loaded in a cycle, and the factory would read the model before it exists (Cannot access 'Flight' before initialization). A factory is registered when its module is loaded: a test imports the factories it uses, as a new application's tests import database/factories/UserFactory.

Factory States

State manipulation methods allow you to define discrete modifications that can be applied to your model factories in any combination. For example, your UserFactory factory might contain a suspended state method that modifies one of its default attribute values.

State transformation methods typically call the state method provided by laraflare's base factory class. The state method accepts a closure which will receive the object of raw attributes defined for the factory and should return an object of attributes to modify:

/**
 * Indicate that the user is suspended.
 */
suspended(): this {
  return this.state((attributes) => {
    return {
      account_status: 'suspended',
    };
  });
}

"Trashed" State

If your Eloquent model can be soft deleted, you may invoke the built-in trashed state method to indicate that the created model should already be "soft deleted". You do not need to manually define the trashed state as it is automatically available to all factories:

import { User } from '../../app/Models/User';

const user = await User.factory().trashed().create();

Factory Callbacks

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

import { Factory } from '@laraflare/framework';
import { User } from '../../app/Models/User';

export class UserFactory extends Factory<User> {
  static override model = User;
  static { Factory.register(this); }

  /**
   * Configure the model factory.
   */
  override configure(): this {
    return this.afterMaking((user: User) => {
      // ...
    }).afterCreating((user: User) => {
      // ...
    });
  }

  // ...
}

A callback may be async; it is awaited before make or create returns.

You may also register factory callbacks within state methods to perform additional tasks that are specific to a given state:

import { User } from '../../app/Models/User';

/**
 * Indicate that the user is suspended.
 */
suspended(): this {
  return this.state((attributes) => {
    return {
      account_status: 'suspended',
    };
  }).afterMaking((user: User) => {
    // ...
  }).afterCreating((user: User) => {
    // ...
  });
}

Creating Models Using Factories

Instantiating Models

Once you have defined your factories, you may use the static factory method provided to your models by the HasFactory mixin in order to instantiate a factory instance for that model. Let's take a look at a few examples of creating models. First, we'll use the make method to create models without persisting them to the database:

import { User } from '../../app/Models/User';

const user = await User.factory().make();

You may create a collection of many models using the count method:

const users = await User.factory().count(3).make();

Note

make, create and raw return promises, so they are awaited: a factory's definition, states and callbacks may all be asynchronous.

Applying States

You may also apply any of your states to the models. If you would like to apply multiple state transformations to the models, you may simply call the state transformation methods directly:

const users = await User.factory().count(5).suspended().make();

Overriding Attributes

If you would like to override some of the default values of your models, you may pass an object of values to the make method. Only the specified attributes will be replaced while the rest of the attributes remain set to their default values as specified by the factory:

const user = await User.factory().make({
  name: 'Abigail Otwell',
});

Alternatively, the state method may be called directly on the factory instance to perform an inline state transformation:

const user = await User.factory().state({
  name: 'Abigail Otwell',
}).make();

Note

Mass assignment protection is automatically disabled when creating models using factories.

Persisting Models

The create method instantiates model instances and persists them to the database using Eloquent's save method:

import { User } from '../../app/Models/User';

// Create a single User instance...
const user = await User.factory().create();

// Create three User instances...
const users = await User.factory().count(3).create();

You may override the factory's default model attributes by passing an object of attributes to the create method:

const user = await User.factory().create({
  name: 'Abigail',
});

Sequences

Sometimes you may wish to alternate the value of a given model attribute for each created model. You may accomplish this by defining a state transformation as a sequence. For example, you may wish to alternate the value of an admin column between Y and N for each created user:

import { Sequence } from '@laraflare/framework';
import { User } from '../../app/Models/User';

const users = await User.factory()
  .count(10)
  .state(new Sequence(
    { admin: 'Y' },
    { admin: 'N' },
  ))
  .create();

In this example, five users will be created with an admin value of Y and five users will be created with an admin value of N.

If necessary, you may include a closure as a sequence value. The closure will be invoked each time the sequence needs a new value:

import { Sequence } from '@laraflare/framework';

const roles = ['admin', 'editor', 'viewer'];

const users = await User.factory()
  .count(10)
  .state(new Sequence(
    (sequence) => ({ role: roles[Math.floor(Math.random() * roles.length)] }),
  ))
  .create();

Within a sequence closure, you may access the index property on the sequence instance that is injected into the closure. The index property contains the number of iterations through the sequence that have occurred thus far:

const users = await User.factory()
  .count(10)
  .state(new Sequence(
    (sequence) => ({ name: `Name ${sequence.index}` }),
  ))
  .create();

For convenience, sequences may also be applied using the sequence method, which simply invokes the state method internally. The sequence method accepts a closure or objects of sequenced attributes:

const users = await User.factory()
  .count(2)
  .sequence(
    { name: 'First User' },
    { name: 'Second User' },
  )
  .create();

Factory Relationships

Has Many Relationships

Next, let's explore building Eloquent model relationships using laraflare's fluent factory methods. First, let's assume our application has an app/Models/User.ts model and an app/Models/Post.ts model. Also, let's assume that the User model defines a hasMany relationship with Post. We can create a user that has three posts using the has method provided by laraflare's factories. The has method accepts a factory instance:

import { Post } from '../../app/Models/Post';
import { User } from '../../app/Models/User';

const user = await User.factory()
  .has(Post.factory().count(3))
  .create();

By convention, when passing a Post model to the has method, laraflare will assume that the User model must have a posts method that defines the relationship. If necessary, you may explicitly specify the name of the relationship that you would like to manipulate:

const user = await User.factory()
  .has(Post.factory().count(3), 'posts')
  .create();

Of course, you may perform state manipulations on the related models. In addition, you may pass a closure-based state transformation if your state change requires access to the parent model:

const user = await User.factory()
  .has(
    Post.factory()
      .count(3)
      .state((attributes, user) => {
        return { user_type: (user as User).type };
      })
  )
  .create();

Using Magic Methods

For convenience, you may use laraflare's magic factory relationship methods to build relationships. For example, the following example will use convention to determine that the related models should be created via a posts relationship method on the User model:

const user = await User.factory()
  .hasPosts(3)
  .create();

When using magic methods to create factory relationships, you may pass an object of attributes to override on the related models:

const user = await User.factory()
  .hasPosts(3, {
    published: false,
  })
  .create();

You may also pass multiple attribute objects to create related models with per-model state. laraflare will apply each object in sequence:

const user = await User.factory()
  .hasPosts(
    { title: 'First Post' },
    { title: 'Second Post' },
    { title: 'Third Post' },
  )
  .create();

You may provide a closure-based state transformation if your state change requires access to the parent model:

const user = await User.factory()
  .hasPosts(3, (attributes: Record<string, unknown>, user: User) => {
    return { user_type: user.type };
  })
  .create();

Belongs To Relationships

Now that we have explored how to build "has many" relationships using factories, let's explore the inverse of the relationship. The for method may be used to define the parent model that factory created models belong to. For example, we can create three Post model instances that belong to a single user:

import { Post } from '../../app/Models/Post';
import { User } from '../../app/Models/User';

const posts = await Post.factory()
  .count(3)
  .for(User.factory().state({
    name: 'Jessica Archer',
  }))
  .create();

If you already have a parent model instance that should be associated with the models you are creating, you may pass the model instance to the for method:

const user = await User.factory().create();

const posts = await Post.factory()
  .count(3)
  .for(user)
  .create();

Using Magic Methods

For convenience, you may use laraflare's magic factory relationship methods to define "belongs to" relationships. For example, the following example will use convention to determine that the three posts should belong to the user relationship on the Post model:

const posts = await Post.factory()
  .count(3)
  .forUser({
    name: 'Jessica Archer',
  })
  .create();

Many to Many Relationships

Like has many relationships, "many to many" relationships may be created using the has method:

import { Role } from '../../app/Models/Role';
import { User } from '../../app/Models/User';

const user = await User.factory()
  .has(Role.factory().count(3))
  .create();

Pivot Table Attributes

If you need to define attributes that should be set on the pivot / intermediate table linking the models, you may use the hasAttached method. This method accepts an object of pivot table attribute names and values as its second argument:

import { Role } from '../../app/Models/Role';
import { User } from '../../app/Models/User';

const user = await User.factory()
  .hasAttached(
    Role.factory().count(3),
    { active: true }
  )
  .create();

You may provide a closure-based state transformation if your state change requires access to the related model:

const user = await User.factory()
  .hasAttached(
    Role.factory()
      .count(3)
      .state((attributes, user) => {
        return { name: `${(user as User).name} Role` };
      }),
    { active: true }
  )
  .create();

You may also pass an array of pivot objects to provide unique pivot data for each related model:

const user = await User.factory()
  .hasAttached(
    Role.factory(),
    [
      { active: true },
      { active: false },
    ]
  )
  .create();

If you already have model instances that you would like to be attached to the models you are creating, you may pass the model instances to the hasAttached method. In this example, the same three roles will be attached to all three users:

const roles = await Role.factory().count(3).create();

const users = await User.factory()
  .count(3)
  .hasAttached(roles, { active: true })
  .create();

Using Magic Methods

For convenience, you may use laraflare's magic factory relationship methods to define many to many relationships. For example, the following example will use convention to determine that the related models should be created via a roles relationship method on the User model:

const user = await User.factory()
  .hasRoles(1, {
    name: 'Editor',
  })
  .create();

Polymorphic Relationships

Polymorphic relationships may also be created using factories. Polymorphic "morph many" relationships are created in the same way as typical "has many" relationships. For example, if a Post model has a morphMany relationship with a Comment model:

import { Post } from '../../app/Models/Post';

const post = await Post.factory().hasComments(3).create();

Morph To Relationships

Magic methods may not be used to create morphTo relationships. Instead, the for method must be used directly and the name of the relationship must be explicitly provided. For example, imagine that the Comment model has a commentable method that defines a morphTo relationship. In this situation, we may create three comments that belong to a single post by using the for method directly:

const comments = await Comment.factory().count(3).for(
  Post.factory(), 'commentable'
).create();

Polymorphic Many to Many Relationships

Polymorphic "many to many" (morphToMany / morphedByMany) relationships may be created just like non-polymorphic "many to many" relationships:

import { Tag } from '../../app/Models/Tag';
import { Video } from '../../app/Models/Video';

const video = await Video.factory()
  .hasAttached(
    Tag.factory().count(3),
    { public: true }
  )
  .create();

Of course, the magic has method may also be used to create polymorphic "many to many" relationships:

const video = await Video.factory()
  .hasTags(3, { public: true })
  .create();

Defining Relationships Within Factories

To define a relationship within your model factory, you will typically assign a new factory instance to the foreign key of the relationship. This is normally done for the "inverse" relationships such as belongsTo and morphTo relationships. For example, if you would like to create a new user when creating a post, you may do the following:

import { Str } from '@laraflare/framework';
import { User } from '../../app/Models/User';

/**
 * Define the model's default state.
 */
override definition(): Record<string, unknown> {
  return {
    user_id: User.factory(),
    title: 'A Post Title',
    content: Str.random(200),
  };
}

If the relationship's columns depend on the factory that defines it you may assign a closure to an attribute. The closure will receive the factory's evaluated attribute object, and may be async:

/**
 * Define the model's default state.
 */
override definition(): Record<string, unknown> {
  return {
    user_id: User.factory(),
    user_type: async (attributes: Record<string, unknown>) => {
      return (await User.find(attributes.user_id as number))?.type;
    },
    title: 'A Post Title',
    content: Str.random(200),
  };
}

Recycling an Existing Model for Relationships

If you have models that share a common relationship with another model, you may use the recycle method to ensure a single instance of the related model is recycled for all of the relationships created by the factory.

For example, imagine you have Airline, Flight, and Ticket models, where the ticket belongs to an airline and a flight, and the flight also belongs to an airline. When creating tickets, you will probably want the same airline for both the ticket and the flight, so you may pass an airline instance to the recycle method:

await Ticket.factory()
  .recycle(await Airline.factory().create())
  .create();

You may find the recycle method particularly useful if you have models belonging to a common user or team.

The recycle method also accepts a collection of existing models. When a collection is provided to the recycle method, a random model from the collection will be chosen when the factory needs a model of that type:

await Ticket.factory()
  .recycle(airlines)
  .create();
Adapted from Laravel's documentation, Copyright (c) Taylor Otwell, used under the MIT License.