Incorrect value for column with Laravel 4

I have a column created as follows in my Laravel 4 migration:

public function up()
{
    Schema::create(
        'templates',
        function (Blueprint $table) {
            $table->increments('id');
            // Omitted fields...
            $table->smallInteger('pages')->default(0);

            $table->timestamps();
            $table->softDeletes();
        }
    );
}

When I try to save the entity using

$entity->save();

in my controller, I get an error for that particular column when the field value is empty:

SQLSTATE[HY000]: General error: 1366 Incorrect integer value: '' for column 'pages' at row 1

I can fix this by creating a mutator in the model like so:

public function setPagesAttribute($value)
{
    if (empty($value)) {
        $this->attributes['pages'] = 0;
    }
}

But isn't Laravel / Eloquent supposed to be doing that in any case?

I'm just thinking, I'm doing something wrong here...

Answers


I've discovered a solution online: http://www.garethalexander.co.uk/tech/mysql-5-incorrect-integer-value-column-id-row-1

Simply do the following:

  • edit my.cnf
  • comment out the line
    • sql-mode="STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"
  • And run $ mysql.server restart

The problem is that an empty string is getting passed to the query for the Pages field (the default will only trigger if there's no value being passed for the field). I'm not sure how you're building your entity object, but you basically shouldn't be setting entity->pages at all when you want it to use the default value.

If you're getting pages via Input variables, using either Input::get('pages', 0) or Input::get('pages', null) should fix the problem.


Need Your Help

Single page applications and <form> elements

javascript html ajax forms single-page-application

Are there still any benefits of using a &lt;form&gt; element instead of let's say a &lt;div&gt; element in the context of a single page application? The purpose of the &lt;form&gt; element makes se...

Why do mobile browsers load my page completely zoomed-in?

android iphone css mobile zoom

I'm currently working on a site for a client (still a work in progress) and trying to fix some of the mobile issues on the site.