Generating dummy data with Laravel

Andy Haxby


On one of the projects I worked on we needed realistic looking dummy data. Instead of just hardcoding this in the database, we wanted to generate it. Luckily for us, Laravel had just the tools for this!

Before we start on this, you’ll need the following configured properly already:
– Database models
– Migrations
– We’ll be using this package, so make sure you install it. If you use Laravel 5 or higher you won’t have to install this.

Getting started

First we need to create a seeder, let’s call this file DummyDataSeeder.php, we will place this in database/seeds. In this file we basicly define what classes we want to generate data for and how many rows of them. A seeder should always have a run() function. This is pretty self explanatory, but in your run() function you define what seeds you want to run. It will look like this:

    class DummyDataSeeder extends Seeder{
        public function run() {
            //your code for generating data

Let’s say we want to create dummy data for 20 users, first we import the user model at the top of the file, also make sure to import the seeder class:

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

Then, we need to tell the seeder it needs to create the users:

    factory(User::class, 20)->create();

Creating a factory

Now we just told the seeder to generate 20 users, but it doesn’t know what to put in the users yet. Let’s fix that now using a factory.

In a factory you basically define what a user actually is, and what kind of properties it is going to have. You might think of it a bit as writing a table in MySQL. The only difference is that we define what data it is going to have, not what data it should have. For this reason be sure your factory is in line with your database models and migrations, trying to generate fake dummy text and putting them in a field that has a type of int is going to throw errors.

Now let’s create our factory, we will be putting this in database/factories, we’re going to call it ModelFactory.php. Our factory will look like this for this small demo:

    use Faker\Generator;

    use App\Models\User;

    $factory->define(User::class, function (Generator $faker) {
        return [ 'email' => $faker->unique()->safeEmail ];

The $factory is an object that Laravel has created for you. The first parameter you are calling on the define function is the class you will be generating dummy data for, and all you need to know about the second parameter is that it returns an array of the created class.

You always need to return an array, in this you might pass as many values as you want. Here, we say that the user has a field called email. Then we tell faker that the value it will generate has to be unique, this is completely optional and depends on your database design, but in my user class I said that a user’s email has to be unique. Because of this I have to tell this to the faker, too. Otherwise it might generate a duplicate email and throw an error.

After I tell the faker that this value has to be unique, I tell it what kind of value it has to generate. In this case a simple email address. You can check what kind of values you can generate here.

Another example

This one case of creating dummy data we just made is quite simple, but it might look like something like this, too:

    $factory->define(Employee::class, function (Generator $faker) {
    $fname = '';
    $gender = '';
    $plname = $faker->randomElement(['', 'a', 'de', 'der', 'den']);
    $lname = $faker->lastName;

    $x = rand(1, 4);

    switch( $x ) {
        case 1:
                $fname = $faker->firstNameFemale;
                $gender = 'female';
        case 2:
                $fname = $faker->firstNameMale;
                $gender = 'male';
        case 3:
                $fname = $faker->firstNameFemale;
                $gender = 'other';
        case 4:
                $fname = $faker->firstNameMale;
                $gender  = 'other';

    return [
        'email' => fakeEmail($fname,$plname,$lname),
        'phone_number' => $faker->e164PhoneNumber,
        'first_name' => $fname,
        'prefix_last_name' => $plname,
        'last_name' => $lname,
        'birth_date' => $faker->dateTimeBetween($startDate = '-90 years', $endDate = '-16 years', $timezone = date_default_timezone_get()),
        'gender' => $gender,
        'street' => $faker->streetName,
        'house_number' => $faker->numberBetween($min = 0, $max = 200),
        'zip_code' => $faker->postcode,
        'city' => $faker->city,
        'img_path' => "images/" . $faker->md5 . ".jpg",

This code isn’t very complex either, but it shows what is exactly possible with generating fake data.

Actually generating the data

But we aren’t done yet, we have written the code, but we don’t have any way of running it yet. Let’s fix that now. Luckily, a file for this has already been created. It is located in database/seeds/ and is called DatabaseSeeder.php;

It will look something like this:

    use Illuminate\Database\Seeder;
    use Illuminate\Support\Facades\App;

    class DatabaseSeeder extends Seeder {
        public function run() {
            //code for generating data

For now, we will simply add this line in the run() function:


Now that we have written the fake data, all that we have left to do is to run it. The command we have to use for this is the same as the one you use to generate the database without dummy data, but now we add the option –seed: php artisan migrate --seed. This command will run all of the Seeders that you have put in the run function in the DatabaseSeeder.php file.

Good job! You have now created your Dummy Data!






Andy Haxby


Andy is the founder of Competa and FTSF. He is always looking to find ways to improve sustainability with software.

Related articles

The latest articles on business and tech information.