Summer Sale! All accounts are 50% off this week.

DigitalMasters's avatar

Extending Factories

Hey guys, i have an own laravel package that holds models, migrations and factories. Now i am curious how i can extend the given factories of the package in my application which has this packe installed. For example the customer factory in the package returns

return [
'name' => $this->faker->randomName,
 'customer_number' => $this->faker->randomDigit
];

But the factory in the application should return a number out of a specific number range. The other values like name in this case can be as they are.

My customer model in the application extends the customer model of the package.

Im happy for every hint Thanks in advance

0 likes
2 replies
tykus's avatar
tykus
Best Answer
Level 104

You can merge the raw attributes from the package with the extra/overrides in the application's Factory:

// database/factories/CustomerFactory.php
public function definition()
{
    return array_merge(
        \Vendor\Models\Customer::factory()->raw(),
        ['customer_number' => $this->faker->numberBetween($low, $high)]
    );
}
DigitalMasters's avatar

@tykus Thanks for the hint.

With addition that i have to overwrite the newFactory method in the vendor model. Otherwise there is a namespace fuckup with get_called_class()

protected static function newFactory()
{
       return Vendor\Models\CustomerFactory::new();
 }

Please or to participate in this conversation.