Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon Laravel factory override attribute


Laravel factory override attribute


To override attributes when creating a model using a factory in Laravel, you can pass an array of attributes to the `create()` method:

php
factory(Api\User::class)->create(['country_id' => 1]);

This will create an instance of `Api\User` with the `country_id` attribute set to `1`, overriding the default value defined in the factory's `definition()` method[1].

You can also use factory states to define discrete modifications to your model factories. For example, you might have a `suspended` state method that modifies one of the default attribute values[2]:

php
$user = User::factory()->suspended()->create();

When using magic methods to create factory relationships, you can pass an array of attributes to override on the related models[2]:

php
$user = User::factory()
    ->hasPosts(3, ['published' => false])
    ->create();

It's important to note that the overrides must be passed after any relationship methods, as the overrides always go before any relationship methods[4].

If you are still having issues overriding attributes, make sure you are not using the database transactions trait, which can cause unexpected behavior. Also, ensure you are using a separate testing database and running `migrate:refresh` before each test[5].

Citations:
[1] https://laracasts.com/discuss/channels/testing/overriding-values-in-model-factories
[2] https://laravel.com/docs/11.x/eloquent-factories
[3] https://stackoverflow.com/questions/46951109/laravel-model-factory-override-default-state
[4] https://laracasts.com/discuss/channels/testing/laravel-8-factories-access-overriden-attributes-from-definition
[5] https://laravel.io/forum/01-14-2016-cannot-override-model-factories-default