Creating Seed Data

Steps in creating a new seed data file

Adding new seed data is as simple as creating a new PHP file with a name matching the entity's name.

Creating Seed Data classes

When creating a new seed data class, extend the SeedData abstract class. There are two abstract classes that can be used, SeedData and RawSeedData.

The seed generator is looking for the data() method to populate the database using the returned array.

RawSeedData abstract class

For RawSeedData, the $table property must be set to the name of the database table.

abstract class RawSeedData implements RawSeedDataInterface
{
    ...
    /**
     * @var string The database table name
     */
    protected string $table;
    
    ...
}

SeedData abstract class

The SeedData class uses an Eloquent model to determine the table structure.

Implement the type() method in the seed data class to return the model class name.

Example from RawSeedData

Example extending SeedData

Updating/Adding a Seeder File

After creating a new seed data class, the seeds() method in the module's corresponding seeder class must be updated. Every module should have a seeder class located in the following path:

app/Modules/{MODULE_NAME}/Database/Seeds

This file's name should match the module name suffixed with Seeder. For example, the Absences module seeder class file would be:

app/Modules/Absences/Database/Seeds/AbsencesSeeder.php

This seeder class is responsible for importing and initializing all the seed data classes that belong to that module.

If the module doesn't already have a seeder file, create one using the snippet below and other seeder files as an example.

  • Replace {MODULE_NAME} with the modules name

  • Replace {SEED_DATA_CLASS_NAME} with the seed data class name

Registering seeder class

Example

Replace {MODULE_NAME} with the module's name.

Registering the database service provider

To register the database service provider, add it to the module service provider (if this was not done already).

Example

Defining timestamps in Seed Data

If seed data needs to include a timestamp relative to today's date, then Laravel's Carbon class should be used.

Carbon can also be used to create a timestamp from a date string.

Use timestamp property of Carbon objects to store the actual timestamp in seed data records.

Official Carbon documentation

Article on using Carbon

Last updated