3
votes

In a model I have created custom timestamps:

const CREATED_AT = 'fil_ts';
const UPDATED_AT = 'fil_ts';

Basically the idea is that CREATED_AT timestamp will get updated whenever record is changed (in other words: I would have just one timestamp which acts as created and updated timestamp).

How do I make these custom timestamps appear in the database's table trough migrations? Do I need to create them in the migration file when I create the table?


1. Do i need to define custom timestamps in migration like this

$table->timestamp('fil_ts');
$table->timestamp('fil_ts');

2. or like this

$table->timestamps();

So far neither of these methods worked. With the first method I get an error that I can't have same named variables (which is logical, but I don't know other way how to make SINGLE timestamp act as CREATED_AT and UPDATED_AT).

If I use the second method it just creates default timestamps.

My end goal: a single custom timestamp that acts like created_at and updated_at. First it gets creation timestamp and then it keeps updated.


Update

Even if the custom timestamps names are different I still get error when I run php artisan migrate:

Timestamps in the model:

   const CREATED_AT = 'file_created';
   const UPDATED_AT = 'file_updated';

Timestamps in the migration:

 $table->timestamp('file_created');
 $table->timestamp('file_updated');

Doctrine\DBAL\Driver\PDOException::("SQLSTATE[42000]: Syntax error or access violation: 1067 Invalid default value for 'file_updated'")

Solution

Code in the model: Need to disable default timestamps

public $timestamps = false; 
const CREATED_AT = 'fil_ts';
const UPDATED_AT = 'fil_ts';

Code in the migration

$table->timestamp('fil_ts'); 
1

1 Answers

3
votes

In your model disable the default timestamp by writing the following code.

public $timestamps = false; 

To create your own timestamp use this code.

This will create one timestamp column.

$table->timestamp('fil_ts'); 

Reference:https://laravel.com/docs/5.6/migrations