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

ajithlal's avatar

custom timestamp field is not returning timestamp with timezone

I have a field in my user's table last_seen type is timestamp. storing the current timestamp when user login on the system.

Customer::where('id', Auth::user()->id)->update(['last_seen' => Carbon::now()]);

When I retrieve the info, I'm getting date time string as below.

"last_seen": "2023-01-16 12:03:16",

I want to get "2023-01-12T05:19:25.000000Z" something like this. same like created_at. I tried to cast the type to datetime in my model. but still getting the date time string.

0 likes
2 replies
tisuchi's avatar

@ajithlal You can try using the toIso8601String() method on the Carbon instance when you're updating the last_seen field. This will format the timestamp as an ISO-8601 string, which is the format that you're looking for.

Customer::where('id', Auth::user()->id)->update(['last_seen' => Carbon::now()->toIso8601String()]);

You can also use toDateTimeString() method which will return the format as 'Y-m-d H:i:s'

Customer::where('id', Auth::user()->id)->update(['last_seen' => Carbon::now()->toDateTimeString()]);

Another way to achieve this is, you can add a accessor to your Model,

public function getLastSeenAttribute($value) {
        return Carbon::parse($value)->toIso8601String();
}
ajithlal's avatar

@tisuchi When I directly fetch the data, I'm getting expected result. But When I load the same in relationship not getting the expected result.

Please or to participate in this conversation.