⬡ Lacelium
⌘K
Version 2.x ▾

Database Seeders

Introduction

Lacelium includes the ability to seed your database with test data using seed classes. All seed classes are stored in the database/seeders directory.

By default, a DatabaseSeeder class is defined for you. From this class, you may use the call method to run other seed classes, allowing you to control the seeding order.

Writing Seeders

To generate a seeder, execute the make:seeder console command. All seeders generated by the framework will be placed in the database/seeders directory:

php console make:seeder UserSeeder

A seeder class only contains one method by default: run. This method is called when the db:seed command is executed. Within the run method, you may insert data into your database however you wish:

<?php

declare(strict_types=1);

namespace Database\Seeders;

use App\Models\User;
use Lacelium\Core\Database\Seeder;
use Lacelium\Core\Database\DB;

class UserSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        DB::table('users')->insert([
            'name' => 'Admin User',
            'email' => 'admin@lacelium.test',
            'password' => password_hash('password', PASSWORD_ARGON2ID),
            'role' => 'administrator',
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s'),
        ]);

        // You may also use Eloquent models directly:
        User::create([
            'name' => 'Demo Member',
            'email' => 'demo@lacelium.test',
            'password' => password_hash('secret123', PASSWORD_ARGON2ID),
            'role' => 'member',
        ]);
    }
}

Calling Additional Seeders

Within the main DatabaseSeeder class, you may use the call method to execute additional seed classes. Using the call method allows you to break up your database seeding into multiple files so that no single seeder class becomes overly large:

<?php

namespace Database\Seeders;

use Lacelium\Core\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     */
    public function run(): void
    {
        $this->call([
            UserSeeder::class,
            CategorySeeder::class,
            TaskSeeder::class,
        ]);
    }
}

Running Seeders

You may execute the db:seed console command to seed your database. By default, the db:seed command runs the Database\Seeders\DatabaseSeeder class:

php console db:seed

Running a Specific Seeder

You may also use the --class option to specify a specific seeder class to run individually:

php console db:seed --class=UserSeeder

Fresh Database & Seeding

You may also seed your database using the migrate:fresh command in combination with the --seed option, which drops all tables and re-runs all of your migrations before seeding:

php console migrate:fresh --seed

Next Steps