I am trying to set a foreign key to null
, deleted_by
does not allow me to save null
as the default value.
I want to be able to set the deleted_by
field to null
when I create a product. I'm currently using a factory to generate the product but I am unable to seed my database as I can't set the field to null
.
Product
table
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('title', 2000);
$table->string('slug', 2000);
$table->string('image', 2000)->nullable();
$table->string('image_mime')->nullable();
$table->integer('image_size')->nullable();
$table->longText('description')->nullable();
$table->decimal('price', 10, 2);
$table->foreignId('created_by')->references('id')->on('users')->nullable();
$table->foreignId('updated_by')->references('id')->on('users')->nullable();
$table->softDeletes();
$table->foreignId('deleted_by')->references('id')->on('users')->nullable()->constrained();
$table->timestamps();
});
User
table
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
Product
factory
public function definition()
{
return [
'title' => fake()->text(),
'image' =>fake()->imageUrl(),
'description' => fake()->realText(200),
'price' => fake()->randomFloat(2, 2, 5),
'created_at' => now(),
'updated_at' => now(),
'created_by' => 1,
'updated_by' => 1,
'deleted_by' => NULL,
];
}
Error I am getting
PDOException::("SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'deleted_by' cannot be null")
I don't know why it is not letting me set the default value to null
when I'm setting the field as nullable.