Using Laravel Factories

Hi guys,

This is just a simple note, how to use laravel 9.x model factories.
In the past it was a bit harder and more unclear for me.
More: Eloquent: Factories - Laravel - The PHP Framework For Web Artisans

Lets go:

create your factory (e.g. plugins/acme/pluginname/factory/)

class FilterFactory extends Factory
{
    /**
     * @var string
     */
    protected $model = Filter::class;

    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition()
    {
        return [
            'title' => fake()->name(),
            'identifier' => str_slug(fake()->name()),
        ];
    }
}

add the HasFactory trait to your model
add the newFactory() method to your model

class Filter extends Model
{
    use Validation;
    use SoftDelete;
    use Illuminate\Database\Eloquent\Factories\HasFactory;

    /**
     * @return Factory
     */
    protected static function newFactory(): Factory
    {
        return FilterFactory::new();
    }
}

use the factory in your tests

/** @test */
public function factoriesAreWorking()
{

    /** @var Filter $filter */
    $filter = Filter::factory()->create();
    $this->assertNotEmpty($filter->title);
    $this->assertNotEmpty($filter->identifier);
}
4 Likes

Hey @alexwenzel

Looks great! I didn’t know about factories used in models like this.

1 Like

To follow up on this, we’ve added some helpful commands in v3.3.18

A base class in the rain library to use (helps protect from breaking changes):

use \October\Rain\Database\Factories\HasFactory

A new command for creating factory classes:

Usage:
  create:factory [options] [--] <namespace> <name>

Description:
  Creates a new factory class.

Arguments:
  namespace     App or Plugin Namespace. (eg: Acme.Blog)
  name          The name of the job class to generate. (eg: PostFactory)