Search code examples
phpmysqllaraveltimestampphp-carbon

Laravel, Carbon and Timestamp, how to set default value?


I have a 5.1.26 Laravel project, one of the models have many timestamp fields , they have been all created on the migration by using something like:

$table->timestamp('repaired_at');

on MySQL the field gets a default value of '0000-00-00 00:00:00'

that works great, if I want to check, if an item have NOT been repaired I check for the default value ('0000-00-00 00:00:00') by doing something like:

if (starts_with($item->repaired_at,"-0001")) { 
   // Date Have not been set
} else {
   // Date have been set
}

As Carbon converts '0000-00-00 00:00:00' to "-0001-11-30 00:00:00"

The problem is that I have not figure out a way to set a timestamp field to its default value '0000-00-00 00:00:00'

I need to figure out a way if a date have been set or not... and be able to reset the date to the default value (not set value)... I would like to keep using eloquent so I can simply do something like:

$item->returned_at = DEFAULT_VALUE;

I appreciate any help....


Solution

  • Instead of relying on a negative date, make the particular field nullable and check if the field is null or not.

    This is what your new migration would look like.

    Schema::table('table_name', function(Blueprint $table) {
        $table->timestamp('repaired_at')->nullable()->change();
    });