Laravel 12 Database Seeder: Step-by-Step Guide

Hey there! If you're working on a Laravel 12 project and need sample data for testing, database seeders can save you a lot of time. Instead of manually inserting data, Laravel's seeder lets you generate test data quickly and efficiently.

In this guide, I'll show you how to create and use a database seeder step by step.

Steps to Create a Database Seeder in Laravel 12

Steps to Create a Database Seeder in Laravel 12

 

Step 1: Create a Seeder Class

Run the following Artisan command to generate a new seeder file:

php artisan make:seeder UserSeeder

This will create a UserSeeder.php file in the database/seeders directory.

 

Step 2: Add Data to the Seeder File

Open database/seeders/UserSeeder.php and modify the run method to insert test data.

<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use App\Models\User;
use Illuminate\Support\Facades\Hash;

class UserSeeder extends Seeder
{
    public function run()
    {
        User::create([
            'name' => 'John Doe',
            'email' => '[email protected]',
            'password' => Hash::make('password'),
        ]);
    }
}

 

Step 3: Run the Seeder

Now, you need to execute the seeder using this command:

php artisan db:seed --class=UserSeeder

This will insert the sample user data into your database.

 

Step 4: Seed Multiple Records Using Factories

If you need multiple users, use a factory instead. Update the UserSeeder.php file.

public function run()
{
    \App\Models\User::factory(10)->create();
}

Then, run the seeder again.

php artisan db:seed --class=UserSeeder

 

Step 5: Run All Seeders at Once

To run all seeders in the DatabaseSeeder.php file, first add your seeder inside the run method:

public function run()
{
    $this->call([
        UserSeeder::class,
    ]);
}

Then, run this command to execute all seeders:

php artisan db:seed

 


You might also like:

techsolutionstuff

Techsolutionstuff | The Complete Guide

I'm a software engineer and the founder of techsolutionstuff.com. Hailing from India, I craft articles, tutorials, tricks, and tips to aid developers. Explore Laravel, PHP, MySQL, jQuery, Bootstrap, Node.js, Vue.js, and AngularJS in our tech stack.

RECOMMENDED POSTS

FEATURE POSTS