skip to Main Content

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


  1. One approach would be to make use of the accessor instead of using casts.

    <?php
    
    namespace AppModels;
    
    use IlluminateDatabaseEloquentModel;
    
    class Post extends Model
    {
        /**
         * Get the created at value.
         *
         * @param  Carbon  $value
         * @return string
         */
        public function getCreatedAtAttribute($value)
        {
            return $value->diffForHumans();
        }
    }
    
    Login or Signup to reply.
  2. Use the Carbon library.

    composer require nesbot/carbon
    

    Model

    use IlluminateSupportCarbon;
    
    class Post extends Model
    {
        // ...
    
        public function getCreatedAtAttribute($value)
        {
            return Carbon::parse($value)->diffForHumans();
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search