Skip to content
Advertisement

Laravel 5.6 time ago in views

<?php

namespace project1HttpControllers;

use IlluminateHttpRequest;
use IlluminateSupportFacadesDB;
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

Advertisement

Answer

First, try an eloquent model.

$users = AppUser::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) {{ CarbonCarbon::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.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement