Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Factories and seeders

An empty database is awkward to develop against: you cannot see what a list of a hundred posts or a page with a long name looks like. Factories and seeders create believable data with one command — for you and for every member of the team.

A factory

A factory describes what one record of a model looks like. It is created with a command:

php artisan make:factory PostFactory

The definition() method sets the column values. The fake() function generates random but realistic data:

namespace Database\Factories;
 
use Illuminate\Database\Eloquent\Factories\Factory;
 
class PostFactory extends Factory
{
    public function definition(): array
    {
        return [
            'title' => fake()->sentence(),
            'body' => fake()->paragraphs(3, true),
            'is_published' => fake()->boolean(80),
        ];
    }
}

Attaching to the model

A model gets the factory() method through the HasFactory trait:

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
 
class Post extends Model
{
    use HasFactory;
}

Creating records

$post = Post::factory()->create();
 
$posts = Post::factory()->count(20)->create();
 
$draft = Post::factory()->create(['is_published' => false]);

The array in create() overrides the values from the factory. The make() method builds an object without saving it to the database.

A factory can create related models too:

$user = User::factory()
    ->has(Post::factory()->count(3))
    ->create();

The user gets three posts with the right user_id.

A seeder

A seeder is a class that fills the database. The main seeder lives in database/seeders/DatabaseSeeder.php:

namespace Database\Seeders;
 
use App\Models\Post;
use App\Models\User;
use Illuminate\Database\Seeder;
 
class DatabaseSeeder extends Seeder
{
    public function run(): void
    {
        User::factory()->create([
            'name' => 'Admin',
            'email' => 'admin@example.com',
        ]);
 
        Post::factory()->count(50)->create();
    }
}

Running

php artisan db:seed
php artisan migrate:fresh --seed

The second command drops every table, runs the migrations again and seeds right away — this is how a database is brought back to its initial state.

Common mistake

migrate:fresh wipes all the data. This command must not be run on a production server: Laravel asks for confirmation, but it is better not to get that far. Seeders with random data are for development and tests only.

Thanks for reading!

Donate to the site — we work hard for you.