Home > Enterprise >  Right way to save timestamps to database in laravel?
Right way to save timestamps to database in laravel?

Time:04-16

As part of a standard laravel application with a vuejs and axios front-end, when I try to save an ISO8601 value to the action_at field, I get an exception.

class Thing extends Model {
    protected $table = 'things';
    // timestamp columns in postgres
    protected $dates = ['action_at', 'created_at', 'updated_at'];
    protected $fillable = ['action_at'];
}

class ThingController extends Controller {
    public function store(Request $request) {
        $data = $request->validate([
            'action_at' => 'nullable',
        ]);
        // throws \Carbon\Exceptions\InvalidFormatException(code: 0): Unexpected data found.
        $campaign = Thing::create($data);
    }
}

My primary requirement is that the database saves exactly what time the client thinks it saved. If another process decides to act on the "action_at" column, it should not be a few hours off because of timezones.

I can change the laravel code or I can pick a different time format to send to Laravel. What's the correct laravel way to solve this?

CodePudding user response:

The default created_at and updated_at should work fine.

  1. You should always set your timezone in your config/app.php to UTC
  2. Add a timezone column or whichever you prefer in your users table
  3. Do the time-offsets in your frontend or api response

Here's a sample code to do the time offset in backend

$foo = new Foo;

$foo->created_at->setTimezone('America/Los_Angeles');

or frontend using momentjs

moment(1650037709).utcOffset(60).format('YYYY-MM-DD HH:mm')

or using moment-timezone
moment(1650037709).tz('America/Los_Angeles').format('YYYY-MM-DD HH:mm')

CodePudding user response:

Let laravel save the timestamp as it and don't change anything on how it has been saved but when you return this data to your front-end app you could change the data format using API Resources your column that called action_at has an instance of Carbon so you could change its format like this example

    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'action_at' => $this->action_at->diffFormHumans() // this will return somethis like this [3 hours ago]
            'updated_at' => $this->updated_at,
        ];
    }

here is an example of diffForHumans()

  • Related