Laravel date cast

147 Views Asked by At

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"

3

There are 3 best solutions below

0
Karl Hill On BEST ANSWER

Use the Carbon library.

composer require nesbot/carbon

Model

use Illuminate\Support\Carbon;

class Post extends Model
{
    // ...

    public function getCreatedAtAttribute($value)
    {
        return Carbon::parse($value)->diffForHumans();
    }
}
0
linktoahref On

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

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    /**
     * Get the created at value.
     *
     * @param  Carbon  $value
     * @return string
     */
    public function getCreatedAtAttribute($value)
    {
        return $value->diffForHumans();
    }
}
0
Shoukat Mirza On

To get the desired output, you can specify a create_at attribute cast on your post model.

make sure you have the Carbon library installed in your Laravel project. You can install it by running the following command:

composer require nesbot/carbon

Attribute cast on your post model:

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    protected $casts = [
        'created_at' => 'datetime',
    ];
}

With this cast defined, accessing the created_at property will return an instance of Carbon, allowing you to format it as needed. To get the "2 hours ago" format, you can use the diffForHumans() method provided by Carbon.

Example:

$post = Post::find(1);
$post->created_at->diffForHumans();