Back to Blog
Lesson 19 of the Laravel Fundamentals: From Zero to Your First App course
LaravelJune 25, 20263 min read

Seeding the Database: A Beginner’s Guide to Laravel Factories

Learn how to use database seeding and factories in Laravel to populate your application with realistic dummy data for testing and development.

laraveldatabaseseedingfactoriestestingdevelopmentphpbackend

Previously in this course, we covered working with Eloquent models to interact with your database. Now that you can save and retrieve records, you need a way to fill your application with data without typing it in manually every time you reset your database.

That is where seeding comes in. Seeding allows you to define a set of data that should exist in your database, making your development environment feel real and your testing process consistent.

Why Use Database Seeding?

When you are building your Task Manager, you need tasks to test your Blade loops and UI components. If you only have one task, you can’t verify if your pagination or filtering logic works.

Manual entry is error-prone and tedious. By using seeders, you create a "source of truth" for your development data. You can wipe your database and rebuild your entire state with a single command.

Creating a Database Seeder

Laravel provides a dedicated directory for these files: database/seeders. To create a new seeder, use the Artisan command line:

Bash
php artisan make:seeder TaskSeeder

This creates a class in database/seeders/TaskSeeder.php. Inside, you’ll find a run() method. This is where you put your logic for inserting data.

PHP
namespace DatabaseSeeders;

use Illuminate\Database\Seeder;
use App\Models\Task;

class TaskSeeder extends Seeder
{
    public function run(): void
    {
        Task::create([
            'title' => 'Finish the Laravel course',
            'description' => 'Complete the seeding lesson.',
            'is_completed' => false,
        ]);
    }
}

Using Model Factories for Dummy Data

While you can hardcode data in a seeder, it's rarely enough. You often need 50 or 100 tasks to properly test your layouts. This is where Laravel factories become essential.

Factories use the Faker library to generate random, realistic data like names, sentences, or paragraphs. If you have already generated a model, you likely have a factory class in database/factories.

Open database/factories/TaskFactory.php and define the structure:

PHP
public function definition(): array
{
    return [
        'title' => fake()->sentence(),
        'description' => fake()->paragraph(),
        'is_completed' => fake()->boolean(),
    ];
}

Now, update your TaskSeeder to use this factory to generate multiple records:

PHP
public function run(): void
{
    #6A9955">// Generate 20 tasks
    \App\Models\Task::factory()->count(20)->create();
}

Running Your Seeders

To execute your seeder, you run the following command:

Bash
php artisan db:seed --class=TaskSeeder

If you want to refresh your database entirely—wiping tables and re-running all migrations before seeding—you can combine the commands:

Bash
php artisan migrate:fresh --seed

This is a developer's best friend. Whenever you make a significant change to your database schema, you can reset everything to a known "good" state instantly.

Hands-on Exercise

  1. Generate a TaskSeeder if you haven't already.
  2. Open your TaskFactory and ensure it has definitions for title, description, and is_completed.
  3. Use the factory in your TaskSeeder to create 50 tasks.
  4. Run php artisan migrate:fresh --seed and verify that your tasks table in your database browser (or via Tinker) is populated with 50 rows.

Common Pitfalls

  • Forgetting to register the seeder: If you create a custom seeder file that isn't DatabaseSeeder.php, you must call it explicitly in the DatabaseSeeder::run() method using $this->call(TaskSeeder::class); if you want it to run when you call php artisan db:seed without flags.
  • Mass Assignment Errors: If your Task::create() call fails, ensure your model has the $fillable property set correctly. We will cover this in detail in preventing mass assignment, but for now, remember that Eloquent requires you to "whitelist" fields you want to mass-assign.
  • Hardcoding in Tests: Avoid using hardcoded data in your production database seeding for tests. Always lean on factories so that your test suite remains decoupled from specific values. You can read more about mastering Laravel database seeders to keep your datasets maintainable as your app grows.

Recap

Seeding is about creating repeatable environments. By combining Seeders to organize your data logic and Factories to generate large volumes of realistic content, you ensure your application is always ready for testing. This workflow is the backbone of efficient, stress-free development.

Up next: Task Manager: Displaying Real Database Records

Similar Posts