How to Get Timesince or Time ago in Laravel 10

In Laravel 10, you can get the timesince or time ago using the Carbon library. Carbon is a popular library for working with dates and times in PHP.

Here’s an example of how to use Carbon to get the timesince or time ago in Laravel 10.


use Carbon\Carbon;

// Example timestamp
$timestamp = '2022-02-28 10:00:00';

// Get the time since the timestamp
$timeSince = Carbon::parse($timestamp)->diffForHumans();

// Get the time ago from the timestamp
$timeAgo = Carbon::parse($timestamp)->ago();

// Output the results
echo 'Time since: ' . $timeSince;
echo 'Time ago: ' . $timeAgo;


 3 days ago
 3 days before

In the above example, we first import the Carbon class at the top of our file. We then define a $timestamp variable as an example that we want to calculate the time since or a time ago.

We use Carbon::parse() to convert the $timestamp into a Carbon object we can work with.

We then use the diffForHumans() method to get the time since the timestamp in a human-readable format.

We use the ago() method to get the time ago from the timestamp.

You can customize the output format by passing additional parameters to the diffForHumans() method.

$timeSince = Carbon::parse($timestamp)->diffForHumans(['parts' => 2]);

This will return a timestamp like this: “3 days, 4 hours ago”.

Using Eloquent model

You can try an eloquent model.

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

In side your view file.

@foreach($users as $user) 

You can also use the DB class.

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

@foreach($users as $user)

   {{ Carbon\Carbon::parse($user->created_at)->diffForHumans()}}


I hope this will help you!

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.