1

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);
});
1
  • include the test code in your question, factory->make() might do the trick Commented Dec 8, 2020 at 7:31

1 Answer 1

2

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();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.