Skip to content
This repository has been archived by the owner on Dec 11, 2020. It is now read-only.

Add named unique() "bags" #1844

Open
wants to merge 4 commits into
base: master
Choose a base branch
from

Conversation

haggys22
Copy link

I want to seed two table columns independently from each other but with the same set of possible values, e.g. [1, 2, 3, 4, 5, 6, 7, 8]

My Laravel factory and seeder look like this:

// Factory
$factory->define(MyModel::class, function (Faker $faker) {
    return [
        'a' => $faker->unique()->randomElement([1, 2, 3, 4, 5, 6, 7, 8]),
        'b' => $faker->unique()->randomElement([1, 2, 3, 4, 5, 6, 7, 8])
    ];
});
// Seeder
public function run() {
    factory(MyModel::class, 4)->create();
}

Currently, the UniqueGenerator will save the existing values only by function name, e.g. "randomElement". Therefore I can only seed up to 4 models and receive no a value as a b value.

Solution:
With this pull request I propose adding a $bag parameter to the unique() modifier to define independent sets of existing values. The given example factory could then be changed to

$factory->define(MyModel::class, function (Faker $faker) {
    return [
        'a' => $faker->unique('a')->randomElement([1, 2, 3, 4, 5, 6, 7, 8]),
        'b' => $faker->unique('b')->randomElement([1, 2, 3, 4, 5, 6, 7, 8])
    ];
});

This allows generation of up to 8 models with distinct values per column (a and b) but same values using the same formatter for different columns.

When used without the $bag parameter the behavior will not change.

@pimjansen
Copy link
Contributor

Please see #1851

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants