Get started with 33% off your first certification using code: 33OFFNEW

Seeding test data in Laravel, a full guide

3 min read
Published on 1st September 2023

Testing is an integral part of software development, and Laravel provides a robust framework for setting up tests. However, sometimes you need dummy data to test your application efficiently. In Laravel, this is done using seeders and the Faker library. This guide will walk you through creating and seeding test data in a Laravel application.

1. Introduction to Seeding

Seeders in Laravel provide a convenient way to populate your database with sample data. This is particularly useful during the development phase when you want to test your application with real-ish data.

2. Setting Up

Before you can use seeders, make sure you've set up a database and configured your .env file with the correct database connection details.

3. Creating a Seeder

To create a seeder, use the Artisan command-line tool:

php artisan make:seeder UsersTableSeeder

This will generate a new seeder class in the database/seeders directory.

4. Using Faker

Laravel uses the Faker library for generating random data. This library provides a plethora of methods to create data of different types.

You can even create your own formatters in Faker if you have specific format of data you need.

To use Faker in your seeder:

use Faker\Factory as Faker;

public function run()
{
    $faker = Faker::create();

    foreach (range(1, 10) as $index) {
        DB::table('users')->insert([
            'name' => $faker->name,
            'email' => $faker->email,
            'password' => bcrypt('secret'),
        ]);
    }
}

5. Model Factories

While seeders are powerful, Laravel recommends using model factories for generating large sets of test data.

Step 1: Create a factory.

php artisan make:factory UserFactory

This will create a new factory in the database/factories directory.

Step 2: Define the model's default state.

use App\Models\User;

$factory->define(User::class, function (Faker $faker) {
    return [
        'name' => $faker->name,
        'email' => $faker->unique()->safeEmail,
        'password' => bcrypt('password'),
    ];
});

Step 3: Use the factory in your seeder.

public function run()
{
    factory(App\Models\User::class, 50)->create();
}

This will create 50 users with random names, emails, and passwords.

6. Relationships and Test Data

Often, you'll want to create test data that has relationships. For instance, a user might have many posts.

First, you'd define a relationship in the User model:

public function posts()
{
    return $this->hasMany('App\Models\Post');
}

Then, in the Post factory:

$factory->define(App\Models\Post::class, function (Faker $faker) {
    return [
        'user_id' => function () {
            return factory(App\Models\User::class)->create()->id;
        },
        'title' => $faker->sentence,
        'body' => $faker->paragraph,
    ];
});

7. Running Seeders

Once your seeders are set up, you can run them using:

php artisan db:seed --class=UsersTableSeeder

Or to run all seeders:

php artisan db:seed

8. Resetting and Reseeding

If you want to rollback all your migrations, run them again and then run the seeders, you can use:

php artisan migrate:refresh --seed

Seeding test data in Laravel can greatly improve the development and testing process. Using the combination of seeders, the Faker library, and model factories, you can generate realistic data sets to effectively test your application's functionality.

Remember, while this data is great for development and testing, always ensure your production database is secured and not populated with test data.