How to pass variable in related factory laravel

Viewed 218

I'm creating test by PHP Unit on Lumen. I try to pass variable $name to related factory Template --> Attribute.

I have tried this code but not working.

        $name = 'Mulyawan Sentosa';
        factory(TemplateModel::class)->create(
            [
                'id'    => 12
            ]
            )->each(
            function ($template) {
                $template->attributes()->save(
                    factory(TemplateattributeModel::class)->make(
                        [
                            'name'      => $name
                        ]
                    )
                );
            }
        );

How to do this? Thank you!

1 Answers

You need to pass the variable inside use keyword parameter to use the variable inside the closure function.

$name = 'Mulyawan Sentosa';

factory(TemplateModel::class)->create(
            [
                'id'    => 12
            ]
        )->each(
            function ($template) use($name) {
                $template->attributes()->save(
                    factory(TemplateattributeModel::class)->make(
                        [
                            'name'      => $name
                        ]
                    )
                );
            }
        );

For more information, visit the PHP documentation

Related