How to solve the "doesn't have a default value" error in Laravel

widget

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:

widget

What causes the error?

Here are some possible reasons for the error:

  1. In your model, you did not add those columns to your $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.

  1. 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 = [];

    
    
}

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:

  1. You can edit the migration file and set the 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.

  1. If the value of the 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.

Free Resources