PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, February 10, 2022

[FIXED] Laravel 5.6 time ago in views

 February 10, 2022     laravel-5.6, php     No comments   

Issue

<?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

Solution

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.



Answered By - im-sunil
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing