Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon Laravel factory with parameters


Laravel factory with parameters


To pass parameters to a Laravel factory, you can use the `->state()` method and define a custom state that accepts the desired parameters. Here's an example:

1. Define the factory state that accepts parameters:

php
// database/factories/UserFactory.php
$factory->state(App\User::class, 'with_posts', function ($attributes, $faker) {
    return [
        'name' => $faker->name,
        'email' => $faker->unique()->safeEmail,
    ];
})->afterCreating(function ($user, $faker) use ($attributes) {
    $user->posts()->saveMany(
        factory(App\Post::class, $attributes['num_posts'])->make()
    );
});

In this example, we define a `'with_posts'` state that accepts a `num_posts` parameter. The `afterCreating` callback is used to create the associated posts based on the provided `num_posts` value.

2. Use the factory state with parameters in your tests:

php
// tests/Feature/UserTest.php
$user = factory(App\User::class)->states('with_posts')->make([
    'num_posts' => 3,
]);

$this->assertCount(3, $user->posts);

When creating the user instance, we use the `->states()` method to apply the `'with_posts'` state and pass the `num_posts` parameter as an array key-value pair.

This approach allows you to pass parameters to the factory and perform additional operations based on those parameters, such as creating related models or setting specific attribute values.

You can also use factory callbacks to perform complex operations after creating a model, such as:

- Associating related models
- Performing calculations or transformations
- Triggering events or notifications
- Conditional callbacks based on the state of the created model

By leveraging factory callbacks, you can encapsulate complex logic within your factories, making your tests more expressive and maintainable.

Citations:
[1] https://laracasts.com/discuss/channels/laravel/how-to-set-parameters-for-laravel-8-factory
[2] https://laracasts.com/discuss/channels/laravel/pass-parameter-to-factory
[3] https://laravel.com/api/8.x/Illuminate/Database/Eloquent/Factories/Factory.html
[4] https://laravel.com/api/7.x/Illuminate/Database/Eloquent/Factory.html
[5] https://github.com/LaravelDaily/laravel-tips/blob/master/factories.md