How we can directly access overriden attributes (array $attributes) in a Laravel 8 factory definition() method?
Let's say for this given L7 factory:
$factory->define(Product::class, function (Faker $faker, $attributes) {
$taxAmount = $attributes['taxAmount'] ?? $faker->randomElement([0, 1, 8, 18]);
$exemption_reason_code = $attributes['exemption_reason_code'] ?? ($taxAmount === 0 ? $this->faker->randomElement([0, 325, 326]) : null);
return [
'name' => ucwords($faker->words(2, true).$faker->lexify('???')),
'taxAmount' => $taxAmount,
'exemption_reason_code' => $exemption_reason_code,
];
});
If we call the factory like this:
factory(Product::class)->create(['taxAmount' => 0])
In the factory definition, we can easily check if there is an overridden taxAmount attribute or not.
How we can access attributes array in a L8 factory?
Sample L8 factory:
public function definition() : array
{
$taxAmount = $attributes['taxAmount'] ?? $this->faker->randomElement([0, 1, 8, 18]);
$exemption_reason_code = $attributes['exemption_reason_code'] ?? ($taxAmount === 0 ? $this->faker->randomElement([0, 325, 326]) : null);
return [
'name' => ucwords($this->faker->words(2, true).$this->faker->lexify('???')),
'taxAmount' => $taxAmount,
'exemption_reason_code' => $exemption_reason_code,
];
}