Laravel 5.6 time ago in views

Laravel 5.5> just write

{{ $date->created_at->diffForHumans() }}

Returns whatever time ago


First, try an eloquent model.

$users = App\User::orderBy('created_at','desc')->limit(5)->get();

in view

@foreach($users as $user) {{$user->created_at->diffForHumans()}} @endforeach

In Terms for your case

$users = DB::table('users')->orderBy('created_at','desc')->limit(5)->get();

@foreach($users as $user) {{ Carbon\Carbon::parse($user->created_at)->diffForHumans()}} @endforeach

Explanation

The eloquent model automatically get casts to Carbon instance and you can use an all methods

In the case of DB query date (created_at) is not get parse so we have to parse manually.


maybe it would help you

A nice semi-hidden feature of timestamps in Eloquent is that they don't just return strings from the database - they actually return an instance of Carbon, a great extension of PHP's DateTime library. What this means is that a heap of functions (and I mean a heap) are available right on your model's timestamps. It's worth having a read through the GitHub README to see what is available, but one of the coolest methods is diffForHumans(), a handy little function providing the long sought-after "time ago" format we often need.

$user = User::first();
echo $user->created_at->diffForHumans(); // 2 days ago

$user->touch();
echo $user->created_at->diffForHumans(); // a second ago

Or

If created_date is an instance of Carbon\Carbon, you can do:

$row->created_date->diffForHumans()

If it isn't an instance of Carbon, you can do:

(new Carbon\Carbon($row->created_date))->diffForHumans()

Or you add the model property to the $dates casting list in the model, which will cast the property to a Carbon instance whenever you access it (like $user->created_date):

class User
{
    protected $dates = [
        'created_date',
    ];
}

The fields created_at and updated_at are added to this casting list automatically if $timestamps of a model is set to true. Also deleted_at will be added if soft deletes are enabled.