In Laravel, seeders are classes that are used to populate your database with dummy or initial data. They are especially helpful when you want to test your application or need some default data after setting up the database. Think of them as a way to “seed” your database with records automatically.
Here’s a detailed explanation:
1. Purpose of Seeders
- To populate tables with sample or default data.
- Useful for testing and development environments.
- Can be combined with factories to generate large amounts of fake data.
2. How Seeders Work
Seeders are stored in the database/seeders directory. Each seeder class contains a run() method, where you define the data to insert.
Example:
<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
use DB;
class UsersTableSeeder extends Seeder
{
public function run()
{
DB::table('users')->insert([
'name' => 'John Doe',
'email' => 'john@example.com',
'password' => bcrypt('password'),
]);
}
}
3. Running Seeders
- To run all seeders:
php artisan db:seed
- To run a specific seeder:
php artisan db:seed --class=UsersTableSeeder
- You can also refresh the database and seed it in one command:
php artisan migrate:fresh --seed
4. Combining Seeders
You can call multiple seeders from the DatabaseSeeder class:
<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
public function run()
{
$this->call([
UsersTableSeeder::class,
PostsTableSeeder::class,
CommentsTableSeeder::class,
]);
}
}
5. Using Factories with Seeders
Seeders often work with factories to generate fake data:
\App\Models\User::factory(10)->create();
This will create 10 fake users using the User factory.
✅ Summary:
Seeders in Laravel are a way to automatically populate your database with test or default data, making development, testing, and initial setup much easier.
