-1

I am using Laravel Framework 6.16.0 and I am having in my migration the following field:

$table->timestamp('trx_timestamp', 0)->nullable($value = true);

Over my API I get the field the following way:

enter image description here

Currently, I am saving it plainly without converting it. However, this does result in 0000-00-00 00:00:00 values in my db.

Any suggestions what I am doing wrong?

Carol.Kar
  • 4,581
  • 36
  • 131
  • 264
  • 1
    And what do you get on dd? – STA Aug 23 '20 at 18:36
  • 1
    Its better if you format your unix timestamp to date and save in database other wise you need to save it as `int(11)` [What is the data type for unix_timestamp (MySQL)?](https://stackoverflow.com/questions/4125947/what-is-the-data-type-for-unix-timestamp-mysql) – M Khalid Junaid Aug 23 '20 at 18:36

2 Answers2

2

If you wish to save data (currently in timestamp) as a date time, convert it and save. you can do it like this.

$date = Carbon::createFromTimestamp($timeStamp)->format('M d Y');

Or

$date = Carbon::parse($timeStamp)->format('M d Y');

Check the carbon package, it is very useful when working with date times.

Ranga Lakshitha
  • 286
  • 2
  • 14
1

As reference to this post If you need to store unix timestamp you will need an integer column.

In migration file you can define your column as

$table->integer('trx_timestamp');

If you need the formatted date you can take benefit from Mutators and define an accessor in your model as

class YourModel extends Model
{
    /**
     * Get formatted trx_timestamp.
     *
     * @param  int $value
     * @return string
     */
    public function getTrxTimestampAttribute($value)
    {
        return Carbon::createFromTimestamp($value)->toDateTimeString();
    }
}
M Khalid Junaid
  • 63,861
  • 10
  • 90
  • 118