How to use a factory within a factory with Laravel?

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP


How to use a factory within a factory with Laravel?



I have a factory creating StreetAddresses and I want to use it in my factory that creates CreditCards.



GOOD: This behaves as expected, creating a CreditCard object with an stdClass for the street_address and the properties are all good.


<?php
use FuquIoLaravelAccountingOrmCreditCard;
use FuquIoLaravelCommonRelatablesLocatableStreetAddress;
use FuquIoLaravelUserAccessUser;

$factory->define(CreditCard::class, function (FakerGenerator $faker){

$street_address = factory(StreetAddress::class)->make();

return [
'customer_id' => User::root()->getKey(),
'cardholder' => $faker->firstName . ' ' . $faker->lastName,
'nick_name' => $faker->company,
// LOOK HERE: this works
'street_address' => function () use ($street_address) { return (object) $street_address->toArray(); }
];

});



NOT so good: This returns null for the street_address.


<?php
use FuquIoLaravelAccountingOrmCreditCard;
use FuquIoLaravelCommonRelatablesLocatableStreetAddress;
use FuquIoLaravelUserAccessUser;

$factory->define(CreditCard::class, function (FakerGenerator $faker){

$street_address = factory(StreetAddress::class)->make();

return [
'customer_id' => User::root()->getKey(),
'cardholder' => $faker->firstName . ' ' . $faker->lastName,
'nick_name' => $faker->company,
// LOOK HERE AGAIN: this makes a null
'street_address' => function () use ($street_address) { return $street_address; }
];

});



What I'd like, is to produce a CreditCard with a StreetAddress as a property.









By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Makefile test if variable is not empty

Will Oldham

Visual Studio Code: How to configure includePath for better IntelliSense results