Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

t0berius's avatar

use timestamp as primary key

For some kind of realtime chat I only need to store the last 5 messages in mySQL. I'm using this kind of table layout:

https://puu.sh/yq5yz/2f1c8f192b.png

My model:

protected $fillable = [
    'id',
    'user_id',
    'message',
];

protected $dates = [
   'id',
];

public $timestamps = false;

Inserting a new chat messages works fine using:

  $new_chat = new Chat();
  $new_chat->user_id = 1;
  $new_chat->message = $request->message;
  $new_chat->save();

but when I try to get the timestamp from this new created entry it returns:

  Log::info($new_chat->id);     -> 0 
  Log::info(Carbon::create($new_chat->id)->timestamp);  -> -62139158388  

Inside the database itself, the timestamps are stored correctly (see: https://puu.sh/yq5Ho/265154d13f.png ). I just need to get the timestamp of them for some websockets stuff.

0 likes
5 replies
thomaskim's avatar

Using a timestamp as your primary key is a terrible idea. Life is just much easier to use the standard auto incrementing integer as your primary key, especially since there is no guarantee that two timestamps are absolutely unique from one another.

So, I would suggest auto incrementing your id, and then just having an extra "created_at" timestamp column.

Next, you are getting this error because by default, Laravel expects your primary key to be auto incrementing. If for some reason, you are not doing this, you need to put this in your model:

public $incrementing = false;
jekinney's avatar

@jaheller

Time stamps are strings, Laravel expects integers by default.

  protected $primaryKey = 'uid';
    
    protected $casts = [
        'uid' => 'string',
    ];

Obviously the above is for a uid not ID, but concept is the same.

t0berius's avatar

@jekinney

I've edited my model to:

protected $fillable = [
    'id',
    'user_id',
    'message',
];

protected $dates = [
   'id',
];

protected $primaryKey = 'id';

protected $casts = [
    'id' => 'string',
];

public $timestamps = false;

still the same problem.

BryceSharp's avatar

I agree with @thomaskim you should not use a time stamp as the id. If you remove public $timestamps = false; then you should be able to simply use:

$new_chat = new Chat();
  $new_chat->user_id = 1;
  $new_chat->message = $request->message;
  $new_chat->save();

dd($new_chat->created_at);

Id's are meant to be an unique identifier within the scope of a table and are often used to optimize queries. Time stamps are not guaranteed unique, and are going to be worse for your behind the scenes (inside the database) query optimization. If making this change is creating other errors, I would recommend trying to resolve those versus continuing to use a time stamp for your id.

Please or to participate in this conversation.