How to solve the "doesn't have a default value" error in Laravel
This shot describes what to do in response to a “doesn’t have a default value” error that may occur when trying to insert data into the database.
The image below is an example of what this might look like:
What causes the error?
Here are some possible reasons for the error:
- In your model, you did not add those columns to your
$fillable. Remember, we have$fillableand$guarded.
Fillable describes columns in the table that are allowed to be inserted, and guarded means the model can’t insert to that particular column.
-
You are sending data to the database and exempting fields that are not
nullableor fields that can’t be left empty.For example, you have a table called
usersthat has a field calleddob(date of birth). If you send data from your form anddobdoes not have a value, this error is likely to occur.
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $guarded = [];
}
Solution for the first cause
If$guarded is left empty, that means no field is guarded and every field of the table is unrestricted.
Solution for the second cause
There are two ways to go about solving this:
- You can edit the migration file and set the
dobfield tonullable, like so:
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('lname');
$table->string('nomba');
$table->string('email');
$table->string('dob')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
Then run your migration again (which you can read about here) to give you more insight while migrating.
- If the value of the
dobfield is important, you set it to berequiredfrom your form, like so:
<input name="dob" type="text" required>
This ensures that every time that form is submitted, it has a dob value.
dobis just an instance field in this shot, and it depends on the field name referred in error.