Extracting Time from created_at with Carbon
When working with Laravel's created_at timestamp, developers often need to isolate specific components of the datetime string. While extracting the date portion is a common requirementâoften achieved by formatting the full timestamp into a readable date string like d.m.Yâisolating the time component can trip up those still mastering Carbon's API.
The core issue in your current approach lies in the order of operations within the accessor. You are creating a Carbon instance from the raw database value, but you are only formatting it to return the date part (d.m.Y). To extract the time, you must keep the full Carbon object until after any necessary transformations, then apply a format string that contains only the time directives.
The Direct Approach
Laravel's created_at attribute is typically an immutable timestamp stored in UTC. When accessed via the model accessor, you receive the raw string from the database (e.g., "2023-10-27 14:35:00"). Your existing code correctly initializes a Carbon instance using Carbon::createFromFormat, which is robust for handling various input formats.
To extract just the time, you simply need to change the format() call. Instead of returning a date-only string, return a format that includes the hour, minute, and second. The standard Carbon format string for this is H:i:s.
Here is how you modify your accessor:
public function getCreatedAtAttribute($value)
{
// Ensure we are working with a valid Carbon instance based on the raw DB value
$carbon = Carbon::createFromFormat('Y-m-d H:i:s', $value);
// Return only the time component formatted as HH:MM:SS
return $carbon->format('H:i:s');
}
Handling Edge Cases
While Carbon::createFromFormat is powerful, relying on a hardcoded format string assumes your database strictly adheres to that exact layout. If your application ever switches to storing timestamps without seconds (e.g., Y-m-d H:i) or with milliseconds (Y-m-d H:i:s.u), the above code will throw an exception.
A more resilient pattern involves using Carbon's default parsing capabilities for standard MySQL datetime columns, which usually handle the raw string without needing explicit format arguments, provided the string is valid ISO-8601 compliant:
public function getCreatedAtAttribute($value)
{
// Try to create a Carbon instance directly; fallback if needed
$carbon = Carbon::parse($value);
return $carbon->format('H:i:s');
}
This approach is generally safer because Carbon::parse attempts to guess the format if one isn't provided, though for strict type safety in production systems, explicitly defining the input format (as shown in the first example) remains a best practice.
Formatting Options
Depending on your frontend requirements, you might need different time representations. The H:i:s format returns hours (00-23), minutes, and seconds separated by colons.
If you need 12-hour formats, you can adjust the directive:
h:i:s Agives "02:35:00 PM".H:i Ogives "14:35 +0000" (useful for timezone offset visibility).
Be aware that extracting time this way strips the date entirely. If you later need to display both, consider returning a single formatted string like d.m.Y H:i:s rather than splitting them into separate properties. This prevents ambiguity in your data presentation layer.
Conclusion
Extracting the time from created_at is as simple as adjusting the format string in your accessor's return statement. By leveraging Carbon::format('H:i:s'), you can cleanly isolate the temporal component without altering the underlying data structure. Always ensure your format strings match your database schema to avoid runtime exceptions, and consider whether stripping the date entirely serves your application's needs or if a combined timestamp is more appropriate for your UI.