Laravel Tutorial · Database and Eloquent · Lesson 18 of 27

Factories and Seeders

Generate realistic fake data for development and tests with model factories and states, and fill the database with seeders.

Create a free account to save this page, take notes and track your progress. Sign in

Factories

A factory describes how to make a fake model: php artisan make:factory PostFactory. Its definition() returns attributes, usually using Faker (fake()->name(), fake()->sentence()). Then:

User::factory()->create();                     // one user, saved
User::factory()->count(10)->create();          // ten
Post::factory()->for($user)->count(3)->create();
User::factory()->has(Post::factory()->count(2))->create();
User::factory()->admin()->make();              // a state, not saved (make)

States are named variations (admin(), unverified()), and sequences cycle through values.

Seeders

Seeders fill the database: php artisan make:seeder DemoSeeder, call factories inside run(), list them in DatabaseSeeder, and run php artisan db:seed (or migrate:fresh --seed). Use them for development data, never as a way to change production.

A factory with a state and a sequence
<?php
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Factories\Sequence;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

Schema::create('customers', function (Blueprint $t) {
    $t->id();
    $t->string('name');
    $t->string('email')->unique();
    $t->string('plan');
    $t->boolean('vip')->default(false);
});

class Customer extends Model
{
    use HasFactory;
    public $timestamps = false;
    protected $guarded = [];
    protected static function newFactory() { return CustomerFactory::new(); }
}

class CustomerFactory extends Factory
{
    protected $model = Customer::class;

    public function definition(): array
    {
        return [
            'name' => fake()->name(),
            'email' => fake()->unique()->safeEmail(),
            'plan' => 'free',
        ];
    }

    public function vip(): static
    {
        return $this->state(['plan' => 'pro', 'vip' => true]);
    }
}

fake()->seed(42);   // a fixed seed makes "random" data repeatable (useful in tests)

Customer::factory()->count(4)->state(new Sequence(['plan' => 'free'], ['plan' => 'pro']))->create();
Customer::factory()->vip()->create(['name' => 'Valued Customer']);
$unsaved = Customer::factory()->make();

echo 'customers saved: ', Customer::count(), "\n";
echo 'plans: ', json_encode(Customer::pluck('plan')), "\n";
echo 'vip: ', Customer::where('vip', true)->value('name'), "\n";
echo 'emails look real: ', Customer::all()->every(fn ($c) => str_contains($c->email, '@')) ? 'yes' : 'no', "\n";
echo 'make() is not saved: ', $unsaved->exists ? 'saved' : 'not saved', "\n";

Output

customers saved: 5
plans: ["free","pro","free","pro","pro"]
vip: Valued Customer
emails look real: yes
make() is not saved: not saved

Run this on your computer — see “Get Started” for setup.

Test yourself

What's the difference between factory()->create() and factory()->make()?

  1. No difference
  2. create() saves to the database; make() only builds the model in memory
  3. make() saves twice
  4. create() returns an array
Show answer

Answer: create() saves to the database; make() only builds the model in memory

Was this page helpful?