Eloquent: Seed and Factory — Laravel 10 Discovery Training

In this new chapter we will discover the Seeding and Factory system which will allow you to pre-fill your database with test data. It is very practical during the development phase to simulate a functional application but also for the implementation of functional tests that we will discover later.

The principle of seeding is quite simple, we will have a class DatabaseSeeder in the database folder which will contain a method run() which will contain the instructions to fill the database. To quickly create records, this seeder can rely on another type of class: Factory.

Factory

THE Factory allow you to quickly generate a model with random data. For the generation of this data Laravel relies on the Faker library. You also have an example of Factory included by default for the User model:

<?php

namespace Database\Factories;

use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;

/**
 * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\User>
 */
class UserFactory extends Factory
{
    /**
     * Define the model's default state.
     *
     * @return array<string, mixed>
     */
    public function definition(): array
    {
        return [
            'name' => fake()->name(),
            'email' => fake()->unique()->safeEmail(),
            'email_verified_at' => now(),
            'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
            'remember_token' => Str::random(10),
        ];
    }

    public function unverified(): static
    {
        return $this->state(fn (array $attributes) => [
            'email_verified_at' => null,
        ]);
    }
}

The method definition() returns an array with the base values ​​to save when creating a fake user. The method unverified() allows you to define a specific state in order to more easily create a variation. Once this Factory has been created, we will be able to use it in our seeder using the method factory() on our models.

$user = User::factory()->create();
// Avec un état
$unverifiedUser = User::factory()->unverified()->create();

You can also use this factory to generate multiple records at once.

$users = User::factory()->count(3)->create();

You can discover the methods related to the factory by going to the documentation.

Seeding

Once your DatabaseSeeder filled you can ask Laravel to fill your database using the command.

php artisan db:seed

This command will add the records without erasing the data already present in your database. You start from scratch (relaunch migrations and seeding) using the command.

php artisan migrate:fresh --seed