Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.3 Creating Models Returns "Field doesn't have a default value"

I'm using Laravel and Eloquent for two years and today I've decided to install a fresh Laravel 5.3 and try something with it.

I used an old database schema of mine and created my models, defined fillable columns. This is what my Page model looks like:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Page extends Model
{

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'language',
        'title',
        'slug',
        'url',
        'description',
        'tags',
        'wireframe',
        'order',
        'is_active'
    ];

    public function menus()
    {
        return $this->belongsToMany(Menu::class);
    }
}

url attribute is a TEXT-type column on MySQL so if I don't pass any value to it when creating a model, it should be a empty string. Instead, I keep getting SQLSTATE[HY000]: General error: 1364 Field 'url' doesn't have a default value error.

Here is my attempt to create a Post model:

Page::create([
    'title' => $root_menu['title'],
    'slug' => $root_menu['slug'],
    'language' => $this->language,
    'wireframe' => key(config('cms.wireframe')),
    'order' => 0
]);

Is this a Laravel 5.3 related issue or am I missing something? Thanks in advance for your helps.

like image 944
Guney Cobanoglu Avatar asked Sep 02 '16 22:09

Guney Cobanoglu


2 Answers

The reason for the error has been explained by @Nicklas.

The reason this is happening now, however, is that Laravel 5.3 uses strict mode for MySQL by default.

If you would like to revert to previous behavior, update your config/database.php file and set 'strict' => false for your connection.

like image 157
patricus Avatar answered Oct 25 '22 07:10

patricus


You are trying to insert an object, with no 'URL' attribute, into a table that has a 'URL' column without a default value. So the database can't know what to do with that column.

You can do one of three things.

  1. Fill in the URL value in the create
  2. Change your schema to allow null insertion on URL
  3. Change the URL schema to include a default value. (empty string)

Post your migration or schema, if you need further help.

like image 27
Nicklas Kevin Frank Avatar answered Oct 25 '22 08:10

Nicklas Kevin Frank