Hello Every I want to use Laravel default casts feature, where if I access created_at property of a post model. I would like the following output from the following code:
Code:
$timepassed = $post->created_at;
Desired Output:
2 hours ago
The laravel document provides only one example of casts for date which is :
protected $casts = [
'created_at' => 'datetime:Y-m-d',
];
So when I access $post->created_at, the above casts will output "2023-06-20".
My question is what should I use instead of ‘datetime:Y-m-d’ to get output like: "2 hours ago"
2
Answers
One approach would be to make use of the accessor instead of using casts.
Use the Carbon library.
Model