1

When I try to execute this code (excerpt):

// ####_##_##_######_create_items_table.php
$table->string('seller_sku')->default('')->unique();

// ItemFactory.php
return [
  'seller_sku' => $faker->optional($default = '')->word,
];

and run: php artisan migrate:refresh --seed

it yields:

SQLSTATE[23000]: Integrity constraint violation: 1048 Column
'seller_sku' cannot be null (SQL: insert into `items` (`name`,
`seller_sku`, `category_id`, `current_prize`, `winter`, `updated_at`,
`created_at`) values (facilis, , 44, 131, 1,
2018-03-03 12:18:22, 2018-03-03 12:18:22))

Why is that happening and how can I solve the problem?

2 Answers 2

1

the problem is because first you are telling the laravel to set a default value '' after that you set a unique key .. What if there are to rows with value = '' they wont be unique anymore .. unique keys cannot have any default value.. thats why you are getting an error

Sign up to request clarification or add additional context in comments.

3 Comments

I had no idea that empty strings counts in uniqueness, I thought they would be equivalent to null in that aspect.
no unique keys cant have same values even if it is null or ''
No it can have multiple null. Tested and certified.
0

The problem is solved using $faker->optional(null,'')->word. The faker documentations are kinda misleading, especially for somebody becoming from Python.

But anyway it just happens that duplicate empty strings are not allowed in a not null column so I ended up doing this (excerpt):

// ####_##_##_######_create_items_table.php
$table->string('seller_sku')->nullable()->unique();

// ItemFactory.php
return [
  'seller_sku' => $faker->unique()->optional()->word,
];

I shared the solution that somebody might get in a likewise confusion.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.