0

I'm trying to create two different sets of seeders and attempting to use Laravel's factory states to specify different factories for each seeder. Here is an basic example of a BoopieFactory:

$factory
    ->state(App\Models\Boopie::class, 'one_flavored', function (Faker $faker) {
        return [];
    });

$factory
    ->state(App\Models\Boopie::class, 'two_flavored', function (Faker $faker) {
        return ['something different'];
    });

I was then under the assumption that I could call either factory(\App\Models\Boopie::class, 25)->states('one_flavored')->create(); or factory(\App\Models\Boopie::class, 25)->states('two_flavored')->create();. These result in the above mentioned Unable to locate factory with name [default] [App\Models\Boopie]. error. Am I missing something small here, or is this just a complete mis-understanding of factory states? Or do I also still need to define the factory first and then chain state on? Laravel's docs are usual great, but lack in this department. I was also looking at defineAs (undocumented, but in the eloquent source code) to attempt to create two different aliases for the same class with different returns. Something like:

$factory
    ->defineAs(App\Models\Boopie::class, 'OneFlavor', function (Faker $faker) {
        return [];
    });

$factory
    ->defineAs(App\Models\Boopie::class, 'TwoFlavor', function (Faker $faker) {
        return ['Something different'];
    });

And then I'm trying to call like so: factory('OneFlavor', 25)->create(); and getting the exception: Class 'OneFlavor' not found. Perhaps there's another way to go about this altogether, or I'm just missing something? I have also tried to nest it like so, which seems to be closer but still has the exception: Unable to locate [oneFlavor] state for [App\Models\Boopie].

$factory->define(App\Models\Boopie::class, function (Faker $faker) use ($factory) {
$factory->state(App\Models\Boopie::class, 'oneFlavor', function ($faker) {
    return [];
});

$factory->state(App\Models\Boopie::class, 'twoFlavor', function ($faker) {
    return ['Someting different'];
});
return [];

});

Thanks in advance !

Matt Larsuma
  • 1,456
  • 4
  • 20
  • 52

1 Answers1

0

Ok, solved like so:

$factory->define(App\Models\Boopie::class, function (Faker $faker) {
    return [
        'thingOne' => 'red shirt',
        'thingTwo' => 'blue shirt'
    ];
});

$factory->state(App\Models\Boopie::class, 'usiFlavored', function (Faker $faker) {
    return [
        'thingOne' => 'blue shirt',
        'thingTwo' => 'red shirt'
    ];
});

You need to first define a default factory with attributes and then your various states can specify different values for those attributes.

Matt Larsuma
  • 1,456
  • 4
  • 20
  • 52