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);
}
2 Likes

Hey @alexwenzel

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