How to solve this Closure object cannot have properties in Factory

Viewed 86

I'm refactoring laravel factories. Then I found a define function like below.

$factory->define(EmploymentAllowance::class, function (Faker $faker, array $attributes) {
    $employment = Arr::exists($attributes, 'employment_id')
        ? Employment::where('id', $attributes['employment_id'])->first()
        : Employment::factory()->create();

    return [
        'employment_id' => $employment->id,
        'calendar_id' => fn () => Calendar::factory()->create([
            'company_id' => $employment->company_id,
        ]),
    ];
});

I have refactored this like below.

public function definition()
    {
        $employment = fn (array $attributes) => Arr::exists($attributes, 'employment_id')
            ? Employment::where('id', $attributes['employment_id'])->first()
            : Employment::factory()->create();

        return [
            'employment_id' => $employment->id,
            'calendar_id' => fn () => Calendar::factory()->create([
                'company_id' => $employment->company_id,
            ]),
        ];
    }

Now I'm getting an error like this,

Error: Closure object cannot have properties

I have been trying to fix this for a long time now. How can I fix this ??

1 Answers

You could do it like:

public function definition()
{
    return [
        'employment_id' => fn() => Employment::factory()->createOne()->id, // will only create the Employment if no employment_id is send to the factory
        'calendar_id' => function (array $attributes) {
            $employment = Employment::findOrFail('id', $attributes['employment_id']); // will get the employment using the employment_id, doesn't matter if it was sent to the factory or created by the factory
            return Calendar::factory()->create([
                'company_id' => $employment->company_id,
            ]),
        }
    ];
}
Related