When using Factory States, provide part or a sub array and append instead of overwrite

Published 11 months ago by mstnorris

I have a default Model Factory, and many states that just change parts of the default. One of the keys on the default is an array and I only want to override some of the array (only the keys that I've specified in the state, the others I would like to leave as-is from the default). The whole array is overwritten. Is it possible to do what I want? (Without of course duplicating the same key => values in each of the states.)

Default Content Factory

$factory->define(Content::class, function (Faker $faker) {
    return [
        'uuid' => $faker->uuid,
        'owner' => 'owner-one',
        'content' => [
            'template_data' => [
                'some_key' => 'some value'
            'meta_data' => [
                'owner_name' => 'Owner One',
        'another_key' => 'another value',
        'one_more_key' => 'one more value',

Owner Two's Content Factory State

$factory->state(Content::class, 'owner-two', [
    'owner' => 'owner-two',
    'content' => [
        'meta_data' => [
            'owner_name' => 'Owner Two',

When I use the Owner Two Factory State, the 'template_data' is missing as well as the other values.

11 months ago (1,002,230 XP)

I'm guessing it only works at one level. Not sure how to work around that.


Yes it appears that way, for now I have just duplicated everything which I don't like, but as it doesn't change that frequently I can live with it. But it would be a nice addition to just be able to override the bits I want to change.

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