17
<?php

namespace project1\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use View;

class IndexController extends Controller
{
    public function index() 
    {
          $users  = DB::table('users')->orderBy('created_at','desc')->limit(5)->get();
          return View::make('pages.dashboard.dashboard',['users' => $users]);
    }
}

Is it possible to echo the Time Ago in my View ( pages.dashboard.dashboard ) Something Like,

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

Expecting output like,

1 min ago

4 Answers4

35

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.

im-sunil
  • 434
  • 4
  • 9
4

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.

Namoshek
  • 6,394
  • 2
  • 19
  • 31
Jagdeesh Kumar
  • 1,640
  • 2
  • 13
  • 29
1

Laravel 5.5> just write

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

Returns whatever time ago

0

just write ->diffForHumans(); after your time. like $record->created_date->diffForHumans();

Imad Ullah
  • 929
  • 9
  • 17