Seeding data helps you quickly fill your database with sample information. This makes testing and development easier without typing data manually.
0
0
Seeding data in Laravel
Introduction
You want to test your app with example users and posts.
You need to reset your database with fresh sample data.
You want to share a ready-to-use database setup with your team.
You want to fill lookup tables like countries or categories automatically.
Syntax
Laravel
php artisan make:seeder SeederName
// Inside database/seeders/SeederName.php
public function run()
{
DB::table('table_name')->insert([
'column1' => 'value1',
'column2' => 'value2',
]);
}
// Run all seeders
php artisan db:seedSeeder classes go inside database/seeders folder.
Use php artisan db:seed to run all seeders or php artisan db:seed --class=SeederName for one.
Examples
This creates a seeder to add one user named Alice.
Laravel
php artisan make:seeder UsersTableSeeder
// In UsersTableSeeder.php
public function run()
{
DB::table('users')->insert([
'name' => 'Alice',
'email' => 'alice@example.com',
'password' => bcrypt('password123'),
]);
}Use Laravel factories to create 10 random users easily.
Laravel
public function run()
{
User::factory()->count(10)->create();
}Run only the
UsersTableSeeder without running all seeders.Laravel
php artisan db:seed --class=UsersTableSeederSample Program
This seeder adds one user named John Doe with a hashed password. You run it with the artisan command shown in the comment.
Laravel
<?php namespace Database\Seeders; use Illuminate\Database\Seeder; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Hash; class UsersTableSeeder extends Seeder { public function run() { DB::table('users')->insert([ 'name' => 'John Doe', 'email' => 'john@example.com', 'password' => Hash::make('secret123'), ]); } } // To run this seeder, use: // php artisan db:seed --class=UsersTableSeeder
OutputSuccess
Important Notes
Always hash passwords before inserting users to keep data safe.
You can call other seeders inside DatabaseSeeder.php to organize data setup.
Use factories for large amounts of fake data to save time.
Summary
Seeding fills your database with sample data automatically.
Create seeders with php artisan make:seeder and run them with php artisan db:seed.
Use factories for easy generation of many fake records.