Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

tisuchi's avatar
Level 70

How to use diffForHumans() in Vue

In my database, time stamp is 2016-08-15 02:45:59 like so. Now with VueJS I am able to access this created_at column however how can I use diffForHumans() in vue?

Any idea?

0 likes
21 replies
christopher's avatar

You could use an accessor methods in your Model:

    public function getCreatedAtAttribute($date)
    {
        return Carbon::createFromFormat('Y-m-d H:i:s', $date)->format('Y-m-d');
    }

After this, in this example created_at is returning 2015-09-05 instead of 2015-09-05 00:00:00.

tisuchi's avatar
Level 70

TQ for your response. However, I need to use in Vue JS because my data are displaying from VueJS.

And instead of 2015-09-05 I need to display 5 mints ago format.

1 like
tisuchi's avatar
Level 70

TQ again.

However, nothing working with me.

Here is my code-

@{{ message.created_at }} should I write like this way @{{ message.created_at.diffForHumans() }} in vue JS in order to display in ago formate?

1 like
christopher's avatar

What does your Vue Devtools say? Can you post your message Object? What is the Output from the Laravel Route Endpoint of the message Object?

Are you using Vue inside Laravel Blade Files?

tisuchi's avatar
Level 70

The message object I am calling inside the blade template. The procedure of calling vuejs object is like-

@{{ message.created_at }}

ok, if I use diffForHumans() in blade template, I found following error-

[Vue warn]: Error when evaluating expression "message.created_at.diffForHumans()": TypeError: scope.message.created_at.diffForHumans is not a function
1 like
MikeHopley's avatar

You can use moment.js to format dates and times in javascript.

Use the date-time string straight from your database, and let moment deal with the formatting. You could wrap your formatting in a vue filter.

1 like
simondavies's avatar

Once you pass the result/variable to view message.created_atthats it, its just a static variable and you then cannot use the php/carbon methods on it.

Within the controller/repo which ever class you are returning the results from, is where you need to do your formattting that you want, so then it can be used within your JS.

So say its in your controller this is where you set the data NOT in th js/vuejs

    public function MethodName(){
        $somevar = $this->resturnSomeData();
        return [
            .... // the other bits of the data
            'created' => $somevar->created_at->diffForHumans()
        ];
    
    }
beetuco's avatar

I managed to do it this way with using a vuejs component and fetching data with axios (or Ajax whatever tickles your fancy):

In your Model:

    protected $dates = ['warranty_end_date'];

    protected $appends = ['warrantyDateHumanReadable'];

    public function getWarrantyDateHumanReadableAttribute()
    {
        return $this->warranty_end_date->diffForHumans();
    }

As vue receives an array the 'appends' property kicks in.

In my component template:


    <td>{{ server.warrantyDateHumanReadable }}</td>

and hey presto:

"14 minutes ago"

5 likes
MaverickChan's avatar

import a new package called Moment.js in your npm

then in Vue component , you can make method or a computed property

then it will render like cabon did

RalfGraef's avatar

@beetuco: That exactly solved my problems with my vue js frontend and laravel backend. I'm not sure if I have completly understood the use of $appends in this way, maybe you could explain it a little bit more ...

But thanks a lot!

1 like
beetuco's avatar

@RalfGraef

Good to hear the problem is solved.

Check out this bit in the docs for using appends on your model. Sorry I should have explained it a bit more.

Because my Vue component is calling an API, I'm returning the model instance as JSON, so then in my model I have the accessor getWarrantyDateHumanReadable()... which will be included when returning JSON.

Probably not the best way to do it, but hey it worked haha.

kkhicher1's avatar

I got the solution that you can use anywhere with casting attribute. Check Code below

<?php

namespace App\Casts;

use Carbon\Carbon;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;

class CreateAtCast implements CastsAttributes
{
    /**
     * Transform the attribute from the underlying model values.
     *
     * @param  \Illuminate\Database\Eloquent\Model  $model
     * @param  string  $key
     * @param  mixed  $value
     * @param  array  $attributes
     * @return mixed
     */
    public function get($model, string $key, $value, array $attributes)
    {
        $date = Carbon::parse($value)->diffForHumans();
        return $date;
    }

    /**
     * Transform the attribute to its underlying model values.
     *
     * @param  \Illuminate\Database\Eloquent\Model  $model
     * @param  string  $key
     * @param  mixed  $value
     * @param  array  $attributes
     * @return array
     */
    public function set($model, string $key, $value, array $attributes)
    {
        return $value;
    }
}

in Modal


<?php

namespace App;

use App\Casts\CreateAtCast;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    protected $casts = [
        'email_verified_at' => 'datetime',
        'created_at'        => CreateAtCast::class,
    ];

    protected $dates = ['created_at', 'updated_at'];
}


in vue template just use - user.create_at

DanielRønfeldt's avatar

Heads up: if you're trying to use @kkhicher1 's solution in Laravel 6.x, there's a caveat: it only works on Laravel 7+. The CastsAttributes interface wasn't implemented before Laravel 7.

From The Rubble's avatar

In order to do this inside of Vue, you can install Moment.

First, you'll need to install Moment:

npm install moment

Now you can create a global function to set the format you want, to do so you must open the file resources/js/app.js and put the following code:

import moment from 'moment';

Vue.filter('formatDate', function(value) {
    if (value) {
        return moment(value).fromNow()
    }
});

Now in all your js components you can apply the format as follows:

{{ response.created_at | formatDate }}

The result should be the same as diffForHumans()

From The Rubble's avatar

I replied because it helped me, and I figured I would try to help someone else if they need it. Thanks for the reply, I'll check out the link.

csaba_szekely's avatar

I was looking to get the created_at date in "diffForHumans" format in a vue.js file and found this thread. I know is old but for Laravel 8 I used an "Accessor" approach as described here : https://laravel.com/docs/8.x/eloquent-mutators So in the vue.js file you access the data in the way usually do. Hope this helps someone :)

suren777's avatar

In Your MODEL`

protected $appends = ['created_at_diff'];

public function getCreatedAtDiffAttribute():string { return $this->created_at->diffForHumans(); }

Please or to participate in this conversation.