Database seeding in Laravel is a convenient feature that allows you to populate your database with default or sample data. Whether you're testing, developing, or setting up an application, seeders can save you time and effort.
In this tutorial, we will walk through how to use seeders in Laravel 12 with real-world examples.
🔍 What is a Database Seeder?
A seeder is a class in Laravel that helps you insert sample or default records into your database tables automatically. It’s especially useful for:
- Populating test data for development
- Inserting default users (like an admin)
- Seeding data for dropdowns, roles, permissions, etc.
✅ Prerequisites
Before we begin, make sure:
- Laravel 12 is installed
- Your database is configured in the
.env
file - You have run the migrations:
🧰 Step 1: Create a Seeder
Use Artisan to create a seeder class:
This will generate a file in:
📝 Step 2: Write Seeder Logic
Open UserSeeder.php
and insert the data logic inside the run()
method:
📂 Step 3: Register Seeder in DatabaseSeeder
Open the main DatabaseSeeder.php
file located in database/seeders/
and register your new seeder:
🚀 Step 4: Run the Seeder
To seed your database, run:
To run a specific seeder:
🧪 (Optional) Create and Use Factory
If you want to use Laravel's Factory to generate fake data:
Now, edit database/factories/UserFactory.php
:
Now you can generate 10 users easily:
🔄 Refresh & Seed the Database
You can reset your database and run seeders in one go using:
Or if you want to keep data and rerun seeders only:
🏗️ Seeding Multiple Tables
You can create multiple seeders like PostSeeder
, ProductSeeder
, etc., and register all in DatabaseSeeder.php
:
📌 Use Cases of Seeders
- Testing user login with predefined credentials
- Seeding roles and permissions
- Adding sample blog posts, products, or categories
- Initial setup for admin dashboards
✅ Final Tips
- Use
php artisan migrate:fresh --seed
often during development. - Keep your seeder data realistic using Laravel’s Faker.
- Do not run seeders in production unless absolutely required.
📚 Conclusion
Laravel 12 makes database seeding simple and efficient. Whether you’re building a new app or working in a team, seeders help maintain consistent data across environments and streamline the development process.
With just a few commands, you can have a fully populated database ready for testing.
🧩 Example File Structure