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:
Here are some possible reasons for the error:
$fillable
. Remember, we have $fillable
and $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 nullable
or fields that can’t be left empty.
For example, you have a table called users
that has a field called dob
(date of birth). If you send data from your form and dob
does 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 = [];
}
If$guarded
is left empty, that means no field is guarded and every field of the table is unrestricted.
There are two ways to go about solving this:
dob
field to nullable
, 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.
dob
field is important, you set it to be required
from your form, like so:<input name="dob" type="text" required>
This ensures that every time that form is submitted, it has a dob
value.
dob
is just an instance field in this shot, and it depends on the field name referred in error.