Petar Vasilev
Petar Vasilev

Reputation: 4735

Laravel model factories using same seed for testing purposes

I am trying to set up a default seed for Faker in Laravel which is normally achieved in this way (not in Laravel):

<?php
$faker = Faker\Factory::create();
$faker->seed(1234);

according to Faker's GitHub page.

I am trying to do this so that can I get the same data generated each time so that I can write some unit tests but I have no idea how to do that in Laravel. I've checked Laravel's documentation and tried googling the issue but I found nothing.

Upvotes: 2

Views: 1941

Answers (2)

haz
haz

Reputation: 1636

Here's how to do apply the seed to Faker in Laravel 5.

Inside your app/database/factories directory, create a new file. I called mine SeedFactory.php.

<?php

$factory->faker->seed('1');

That's it!

Now you have consistent random data for your unit testing!

NB: If you only have one or two factories, you could append that line to an existing factory file.


Here's why it works.

When Laravel processes all the files in the app/database/factories directory, it executes them straightaway. The $factory object passed around is an instance of Illuminate\Database\Eloquent\Factory.php, which keeps with it it's own internal Faker\Generator instance.

Also, you won't need to worry about the naming of the file or execution order, because this will get fired before any of the factory callbacks (assuming you did it as instructed in the Laravel docs).

Upvotes: 3

sean xia
sean xia

Reputation: 42

it is easy. Just define a factory. Let's have a look at the default factory shipped with laravel 5.5

File: database/factories/ModelFacotry.php

<?php

/*
|--------------------------------------------------------------------------
| Model Factories
|--------------------------------------------------------------------------
|
| Here you may define all of your model factories. Model factories give
| you a convenient way to create models for testing and seeding your
| database. Just tell the factory how a default model should look.
|
*/

/** @var \Illuminate\Database\Eloquent\Factory $factory */
$factory->define(App\User::class, function (Faker\Generator $faker) {
    static $password;

    // Add this line to original factory shipped with laravel.
    $faker->seed(123);

    return [
        'name' => $faker->name,
        'email' => $faker->unique()->safeEmail,
        'password' => $password ?: $password = bcrypt('secret'),
        'remember_token' => str_random(10),
    ];
});

Then use tinker to test it:

yudu@YududeMacBook-Pro ~/demo> php artisan tinker
Psy Shell v0.8.1 (PHP 7.1.8 — cli) by Justin Hileman
>>> $user = factory(App\User::class)->make()
=> App\User {#880
    name: "Jessy Doyle",
    email: "[email protected]",
}
>>> $user = factory(App\User::class)->make()
=> App\User {#882
    name: "Jessy Doyle",
    email: "[email protected]",
}

Laravel Docs:

how to define and use factory

Seeding

Upvotes: -1

Related Questions