Roni

Model factory for a polymorphic relationship

Posted 5 months ago by Roni

I'm a bit stuck trying something out. Using a Java style inheritance in laravel to get a collection of specialized segments. I'm having a hard time figuring out how to get the model factory working for phpunit, though the code itself works.

ModelFactory


$factory->define(Segment::class, function (Faker $faker) {

    return [
        'quote_id' => create(Quote::class)->id,

        //THIS IS THE BASE ITEM, 
        //NO SEGMENTS EVER EXIST WITHOUT A SPECIFIC IMPLEMENTATION

        'segmentable_id'=> null,
        'segmentable_type'=> '',

        'version' => 1,
        'version_accepted_by_client' => null,
        'version_accepted_by_company' => null,
        'active_version' => 1,
        'company_token' => null,
        'company_token_expiration' => null,
        'client_token' => null,
        'client_token_expiration' => null,

    ];
});


//SPECFIC SEGMENT EXAMPLE

$factory->define(Stone::class, function (Faker $faker) {

    //THIS IS THE SECTION WHERE I NEED TO DEFINE A SEGMENT AND
    //AND OVERRIDE IT'S "SEGMENTABLE" ATTRIBUTES TO THIS
    //CLASSES ID AND CLASSNAME

    // create a segment class here and find a way to override

    return [

        'product_id' => function() { return create(Product::class)->id; },
        'height' => $faker->numberBetween(6,72),
        'width' => $faker->numberBetween(6,72),
        'grouted' => $faker->boolean,
        'sill_on_top' => $faker->boolean,
        'trim_stones' => $faker->numberBetween(0,6),
        'hearth_stones' => $faker->numberBetween(0,6),
        'light_boxes' => $faker->numberBetween(0,6),
        'power_boxes' => $faker->numberBetween(0,6),

    ];
});


The purpose of this is to delegate the calculation of each versioned segment to it's unique object, while allowing a collection of Segments to reside in a project and quote. There is no specific guarantee that any project will have any specific segment. Yet this creates a completely flexible approach.

In code this is not an issue, as I can enforce the relationship in in the boot creating method of the object, or in the controller. I'm a bit new to TDD and factories, is there a "right way" to do this in the model factory?

Thanks

Please sign in or create an account to participate in this conversation.

Laracasts Mascot

Hi, Have We Met Yet?

Did you know that, in addition to the forum, Laracasts includes well over 1000 lessons on modern web development? All for the price of one lunch out per month.

Sign Me Up

Channels

Reply to

Use Markdown with GitHub-flavored code blocks.