Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon What are the differences between afterMaking and afterCreating in Laravel factories


What are the differences between afterMaking and afterCreating in Laravel factories


The main differences between `afterMaking` and `afterCreating` in Laravel factories are:

1. Timing of execution:
- `afterMaking` callbacks are executed after a model instance is created using the `make()` method, but before it is saved to the database.
- `afterCreating` callbacks are executed after a model instance is created using the `create()` method, which saves the model to the database.

2. Database interaction:
- `afterMaking` callbacks are executed without interacting with the database, as the model is not yet saved.
- `afterCreating` callbacks are executed after the model is saved to the database, so you can perform database-related operations within these callbacks.

3. Use cases:
- `afterMaking` callbacks are useful for setting up relationships or performing other operations that don't require the model to be saved to the database.
- `afterCreating` callbacks are useful for setting up relationships, triggering events, or performing other operations that require the model to be saved to the database.

Here's an example to illustrate the differences:

php
$factory->define(App\User::class, function (Faker\Generator $faker) {
    return [
        'name' => $faker->name,
        'email' => $faker->unique()->safeEmail,
    ];
});

$factory->afterMaking(App\User::class, function ($user, $faker) {
    // This will be executed after `make()`, but before saving to the database
    $user->is_admin = true;
});

$factory->afterCreating(App\User::class, function ($user, $faker) {
    // This will be executed after `create()`, after saving to the database
    $user->accounts()->save(factory(App\Account::class)->make());
});

In summary, `afterMaking` is used for operations that don't require the model to be saved, while `afterCreating` is used for operations that require the model to be saved to the database. The choice depends on the specific requirements of your test setup.

Citations:
[1] https://laravel.com/docs/7.x/database-testing
[2] https://cosme.dev/tip/laravel-tip-belongs-to-relationships-in-factories
[3] https://laraveldaily.com/tip/factory-callbacks
[4] https://github.com/laravel/framework/issues/41313
[5] https://laravel-news.com/learn-to-use-model-factories-in-laravel-5-1