How to Create Seeder in Laravel - Step by Step Guide

How to Create Seeder in Laravel - Step by Step Guide

What is a Seeder in Laravel?

In Laravel, seeders are used to populate the database with test or default data. This is useful during development and testing.

Step 1: Create a Seeder Class

Run the following command in the terminal to create a new seeder:

php artisan make:seeder UserSeeder

Step 2: Define Data in the Seeder File

Open the database/seeders/UserSeeder.php file and modify the run method:


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

class UserSeeder extends Seeder {
    public function run() {
        User::create([
            'name' => 'Admin User',
            'email' => 'admin@example.com',
            'password' => Hash::make('password')
        ]);
    }
}
    

Step 3: Run the Seeder

To execute the seeder, run the following command:

php artisan db:seed --class=UserSeeder

Step 4: Run All Seeders

To execute all seeders at once, update the DatabaseSeeder.php file:


use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder {
    public function run() {
        $this->call(UserSeeder::class);
    }
}
    

Now, run:

php artisan db:seed

Conclusion

By following these steps, you can create and run seeders in Laravel to populate your database with test data.

0 Comments