Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon How can I pass dynamic data to a Laravel factory


How can I pass dynamic data to a Laravel factory


To pass dynamic data to a Laravel factory, you can use the `state` method in your factory definition. Here's how you can do it:

1. Define a state method in your factory class that accepts the arguments you want to pass:

php
public function withCompany(int $companyId): static
{
    return $this->state(function (array $attributes) use ($companyId) {
        return [
            'company_id' => $companyId,
        ];
    });
}

2. In your tests or seeding, call the state method and pass the arguments:

php
NaturalPersonFactory::new()
    ->withCompany($company->id)
    ->create();

This will create a `NaturalPerson` model with the `company_id` attribute set to the provided `$company->id` value.

Some key points:

- The state method should return `$this` to allow method chaining.
- The state method can accept arguments and use them to modify the attributes returned by the `state` callback.
- You can define multiple state methods to handle different scenarios.
- The state method is called on the factory instance, not the model class directly.

This approach allows you to pass dynamic data to the factory without modifying the model's attributes directly in the factory definition[1][2][3].

Citations:
[1] https://laracasts.com/discuss/channels/testing/pass-variable-to-factory-laravel-8-not-working
[2] https://laracasts.com/discuss/channels/laravel/call-the-state-of-a-factory-dynamically
[3] https://laracasts.com/discuss/channels/laravel/pass-parameter-to-factory
[4] https://stackoverflow.com/questions/32378215/how-to-pass-arguments-to-laravel-factories
[5] https://laravel.com/docs/7.x/database-testing