I have a unique
index on 3 fields:
public function up(): void
{
Schema::create('items', function (Blueprint $table) {
$table->id();
$table->foreignId('points_id');
$table->foreignId('user_id');
$table->unsignedTinyInteger('status');
$table->timestamp('created_at')->useCurrent();
$table->foreign('user_id')->references('id')->on('users');
$table->foreign('points_id')->references('id')->on('points');
$table->unique(['points_id', 'user_id', 'status']);
});
}
I need to make a factory to create a lot of items, but I can’t prevent the unique
error if I create another item.
My laravel version is: ^9.52.10
.
2
Answers
Just based on your code, you should have a factory like this:
When you use
Model::factory()
and nothing else, it will, 100%, create a new model. You can see that on the documentation.I suggest to configure your ItemFactory to ignore duplication in unique columns:
Factory callbacks are registered using the afterMaking and afterCreating methods and allow you to perform additional tasks after making or creating a model.