Home About Projects Skills Writing Contact
← All writing
Nov 29, 2022 2 min read · Laravel· PHP· Testing

How to Generate the Same Data on Every Run of Your Laravel Seeders

How to Generate the Same Data on Every Run of Your Laravel Seeders

It can get annoying very quickly when you are working on a project and you need the same dataset whenever you refresh your database with your seeders but you keep getting a fresh set of data.

You execute:

php artisan migrate:fresh --seed

And boom — all your data is regenerated with a completely new set. I encountered this frustration so many times until it came to me: "Wait, there is a better way to do this."

I remembered Faker (the library used to generate random data in Laravel) has a way to provide a seed to enable developers to generate the same set of data every time. If you are not familiar with what a seed is in Faker, a quick search returns this:

A seed is essentially an initialising value for a random number generator. For the Faker library this allows you to use a string, number or some value that will be a starting point for all random values generated in sequence. This means, using the same seed produces the same result each time.

So I decided to add this one line that specifies the seed:

$faker->seed(100);

The number 100 passed to seed() is just an arbitrary number. You can pass in any number — provided it stays the same, Faker will always regenerate the same data.

Putting it all together

This is what my database/seeders/DatabaseSeeder.php file looks like:

<?php

namespace Database\Seeders;

use Artisan;
use Faker\Generator;
use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    public function run(Generator $faker)
    {
        $faker->seed(100);

        $this->call(UsersTableSeeder::class);
        // ...
    }
}

Hope this helps someone. ☺️

Bright Nkrumah
Senior software engineer in Kumasi, Ghana. Twelve years of writing PHP, and counting.
More writing