samedi 28 juillet 2018

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 FuquIo\LaravelAccounting\Orm\CreditCard;
use FuquIo\LaravelCommonRelatables\Locatable\StreetAddress;
use FuquIo\LaravelUser\Access\User;

$factory->define(CreditCard::class, function (\Faker\Generator $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 FuquIo\LaravelAccounting\Orm\CreditCard;
use FuquIo\LaravelCommonRelatables\Locatable\StreetAddress;
use FuquIo\LaravelUser\Access\User;

$factory->define(CreditCard::class, function (\Faker\Generator $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.

Aucun commentaire:

Enregistrer un commentaire