Search code examples
phpmysqllaravellaravel-5

why mysql accept null for non-nullable fields


I am learning Laravel 5.1 through laracast fundamentals series and in episode 7 which talk about migrations, I built a table with a migration like this:

public function up()
{
    Schema::create('articles', function (Blueprint $table) {
        $table->increments('id');
        $table->string('title');
        $table->text('body');
        $table->timestamps();
        $table->timestamp('published_at');
    });
}

as it says in episode 10 when I add an article to the database through a form that doesn't have a field for the published_at timestamp, then this should not work and should through an exception that Not Null constraint failed But incredibly the article added to the table. When I look at the table in phpmyadmin structure for the published_at column it doesn't check the null checkbox, so it shouldn't accept null. Is this true?
But then I noticed that the migration sets a default value to 0000-00-00 00:00:00 for the published_at column. Why?! and Will this override the NULL condition? Then I tried to set the default value to none and still the null is not checked. and again I tried to add an article without published_at fields But again a new row was added to the table with the published_at value set to 0000-00-00 00:00:00. any explanation?


I am using wamp server with MySQL v5.6.17 , php v5.5.12


Solution

  • SELECT @@SQL_MODE;.

    If you don't see one of the Strict SQL Modes enabled, then MySQL is using its older behavior, and coercing invalid values into something valid to allow the row to be inserted.

    If strict mode is not in effect, MySQL inserts adjusted values for invalid or missing values and produces warnings.

    Default configuration files shipped with official MySQL Server 5.6 had STRICT_TRANS_TABLES enabled. WAMP may not have followed that same convention, perhaps for backward-compatibility reasons... but the configuration can be changed.