Search code examples
laravellaravel-5laravel-testing

Laravel factory create without calling afterCreating callback


While writing tests I'm creating a model using factory $recipe = factory(Recipe::class)->create() but the RecipeFactory has afterCreating callback that runs and adds relations every time I create a recipe.

Is there a way to skip this callback? I don't want any relations to be created.

RecipeFactory.php afterCreating callback

$factory->afterCreating(Recipe::class, function ($recipe, Faker $faker) {
    $ingredients = factory(Ingredient::class, 3)->create();
    $recipe->ingredients()->saveMany($ingredients);
});

Solution

  • You can define a new state in the factory

    $factory->state(Recipe::class, 'withRelations', [
        //Attributes
    ]);
    

    Then you can define the after hook on the state

    $factory->afterCreating(Recipe::class, 'withRelations', function ($recipe, $faker) {
        $ingredients = factory(Ingredient::class, 3)->create();
        $recipe->ingredients()->saveMany($ingredients);
    });
    

    And remove the existing after create hook.

    Now when you use the default factory - no relations will be created.

    $recipies = factory(Recipe::class, 5)->create();
    

    However if you want to create related records also - you can make use of the withRelations state

    $recipiesWithRelations = factory(Recipe::class, 5)->state('withRelations')->create();