Igor Simic
8 years ago

Set diffForHumans to work with timestamp field in Laravel Model



Setting up human readable dates in Laravel is very easy using Carbon.  In this example we will append custom attribute  which will be human readable date to Laravel model and set the value based on default "created_at" DB field value.

To add a custom attribute in Laravel model output we have to follow these steps:


 1 append field published to model output.  


class YourModelName extends Model
{
    protected $appends=['published'];

Note: this field does not exist in DB we are appending it as attribute to Model output


2 Create method to populate data for this field based on created_at value from DB

class YourModelName extends Model
{
    protected $appends=['published'];

    public function getPublishedAttribute(){
        
            return $this->attributes['created_at'];
        }

Notice name of method, it contains new attribut name  get published attribute, so if your attribute has different name you also have to change method name.



 Now we want to set this date value to human readable format, something like "one hour ago". To achieve this we will use Carbon in Laravel, so first we have to include  Carbon in our Model like this:

use Carbon\Carbon;

Then we have to create a date instance from created_at string value and apply Carbon diffForHumans() method
public function getPublishedAttribute(){
        
            return Carbon::createFromTimeStamp(strtotime($this->attributes['created_at']) )->diffForHumans();
        }


At the end our model should look like this:

use Illuminate\Database\Eloquent\Model;
use Carbon\Carbon;

class YourModelName extends Model
{
    protected $appends=['published'];

    public function getPublishedAttribute(){
        
            return Carbon::createFromTimeStamp(strtotime($this->attributes['created_at']) )->diffForHumans();
        }
}