Laravel General error: 1364 Field ‘column’ doesn’t have a default value
In general ‘column’ doesn’t have a default value which means, you have created a column in the table without default value and not nullable also.
So, there are two solution for this problem, let’s discuss them one by one:
Eloquent Model
If you are sending the data to the server properly with this column and even then you are getting the error ‘column’ doesn’t have a default value. This means either you have missed the column by adding to your $fillable
property in the related model or you have mentioned this column in the $guarded
property of the model.
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Address extends Model { use HasFactory; protected $fillable = [ ‘user_id’, ‘street’, ‘city’, ‘state’, ‘country’ ]; protected $guarded = []; }
You might know about the $fillable
property, it allows columns to insert to the database, so if you have missed the column to add the $fillable
property then you will definitely encounter this error.
Another thing is the $guarded
property, this property of the model prevents the insertion to the database of the defined columns in the $guarded
property.
So, either you have to remove the column from the $guarded property or add the column to the $fillable
property as per your diagnosed issue.
Database migration
Yes, if the model is perfect as per the given information till now. But if you are missing the data in the form or want to make it an optional field then you can change the column to nullable or add default value to it via the database migration. Then you can refresh the database migration.
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateAddressTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('addresses', function (Blueprint $table) { $table->id(); $table->foreignId('user_id'); $table->string(‘city’); $table->string('state')->nullable(); $table->string('country'); $table->string('street'); $table->tinyInteger(‘status’)->default(0); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('addresses'); } }
In the above example, we have taken the “state” column and made it nullable. Now, state will be an optional field in the form. Similarly we can set the default value to it like we have set for status.
Hope you find this article useful, please comment below for any suggestion or issue with this information.