Reputation: 484
I'm making my web site in Laravel 4 and I have the created_at
& updated_at
fields in the table. I want to make a news system that gives me how much time has passed since the post has been made.
| name | text | created_at | updated_at |
| __________ | __________ | ________________________ | ___________________ |
| news name | news_text | 2013-06-12 11:53:25 | 2013-06-12 11:53:25 |
I want to show something like:
-created 5 minutes ago
-created 5 months ago
if the post is older than 1 month
-created at Nov 5 2012
Upvotes: 3
Views: 8434
Reputation: 26992
Try using Carbon. Laravel already comes with it as a dependency, so there is no need to add it yours.
use Carbon\Carbon;
// ...
// If more than a month has passed, use the formatted date string
if ($new->created_at->diffInDays() > 30) {
$timestamp = 'Created at ' . $new->created_at->toFormattedDateString();
// Else get the difference for humans
} else {
$timestamp = 'Created ' $new->created_at->diffForHumans();
}
As requested, I'll give an example of full integration, on how I think would be the better way to do it. First, I assume I might use this on several different places, several different views, so the best would be to have that code inside your model, so that you can conveniently call it from anywhere, without any hassle.
Post.php
class News extends Eloquent {
public $timestamps = true;
// ...
public function formattedCreatedDate() {
ìf ($this->created_at->diffInDays() > 30) {
return 'Created at ' . $this->created_at->toFormattedDateString();
} else {
return 'Created ' . $this->created_at->diffForHumans();
}
}
}
Then, in your view files, you'd simply do $news->formattedCreatedDate()
. Example:
<div class="post">
<h1 class="title">{{ $news->title }}</h1>
<span class="date">{{ $news->forammatedCreatedDate() }}</span>
<p class="content">{{ $news->content }}</p>
</div>
Upvotes: 11
Reputation: 87719
Require Carbon:
use Carbon\Carbon;
And use it:
$user = User::find(2);
echo $user->created_at->diffForHumans( Carbon::now() );
You should get this:
19 days before
Upvotes: 4