DEV Community

Jarko Vihriala
Jarko Vihriala

Posted on

Give arguments to modelfactory

We all know how to create models with modelfactory, and use faker to populate the other stuff there. And yes, if you want to override modelfactory you can do it nicely with arguments to create().

But what if you need to do conditional processing in modelfactory? Yeaaap. Okay, so I did little experiments and discovered this: if you give arguments to the function you use as argument to define, you can pass stuff to modelfactory!

Real world example: snippet from our testing code:

$factory->define(App\Invoice::class, function (Faker\Generator $faker, $arguments = []) {

    if (Arr::exists($arguments, 'invoice_type')) {
        $invoiceType = $arguments['invoice_type'];
    }

So, what we do is we give parameters to create when calling the factory in our tests. Now we can check if $arguments has 'invoice_type' and if so -> we use the data given instead to create new data. We call the factory like so:

        $invoiceInDB = factory(Invoice::class)->create(
            [
                'invoice_type' => Invoice::SERVICE_INVOICE,
                ...
            ]
        );

I know it ain't perfect but hey, it gets the job done!

Top comments (0)