0

I have a table and related model that has a custom timestamp. The migration is set like this:

Schema::create('tests', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name');
    $table->timestamp('expire_at');
    $table->timestamps();
});

And I have set up my Model like so:

class Test {
    protected $dates = [
       'expire_at'
    ];
}

When I try to update the name field only, it sets the expire_at field as same as updated_at field rather than simply not changing it.

$test = Test::find(1);
$test->name = "Changed Value";

// Until here, the expire_at timestamp has its true value
// but on save(), it changes expire_at to updated_at time.

$test->save();

Is there anything I am doing wrong with the protected $dates usage?

senty
  • 12,385
  • 28
  • 130
  • 260
  • You might need to make your `expire_at` column nullable (with `$table->timestamp('expire_at')->nullable()`). You can check if your database has a default value of CURRENT_TIMESTAMP or similar for the expire_at column, which would be setting a value when you leave it null. – Travis Britz Oct 19 '18 at 23:21
  • @TravisBritz Oh yes, you are right - when I check the mysql, it shows `CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP` for the column. Is `->nullable()` the right way to do overcome it? – senty Oct 19 '18 at 23:25
  • Cool, I posted it as an answer – Travis Britz Oct 19 '18 at 23:33

1 Answers1

1

You need to make the column nullable (or remove the default value, CURRENT_TIMESTAMP):

$table->timestamp('expire_at')->nullable();
Travis Britz
  • 5,094
  • 2
  • 20
  • 35
  • 1
    More information about why the `->nullable()` modifier is needed can be found at https://stackoverflow.com/q/22860351/6543983 – Cristian Calara Jan 30 '19 at 19:24