zwl1619
zwl1619

Reputation: 4222

Laravel 5.2 :How to display time like this?

I am using Laravel 5.2, I want to show the article's creation time like this:

created_at                               displaying
in  1  day                                today
2-10 days                                 (2-10) days ago
>10  days                                  show creation date directly

How to do it?
Thanks in advance!

edit:

controller:

  public function show($id)
    {
        $article = Article::findOrFail($id);
        return view('show', compact('article'));
    }

view:

<div class="card">
    <div class="card-block">
        <h4 class="card-title">{{$article->title}}</h4>
        <p class="card-text">{{$article->content}}</p>
        <p class="card-text"><small class="text-muted">{{$article->created_at}}</small></p>
    </div>
</div>

Where should I use Carbon 's diffForHumans()?

Upvotes: 3

Views: 1360

Answers (5)

huuuk
huuuk

Reputation: 4795

You can define accessor for custom attribute

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Carbon\Carbon;

class User extends Model
{

    public function getPrettyCreatedAtAttribute()
    {
        $now = Carbon::now();
        $age = $this->created_at->diffInDays($now);
        if ($age < 2) {
            return 'today';
        }
        elseif ($age < 10) {
            return '(2-10) days ago';
        }
        else {
            return $this->created_at;
        }
    }

}

Then in view

<div class="card">
    <div class="card-block">
        <h4 class="card-title">{{$article->title}}</h4>
        <p class="card-text">{{$article->content}}</p>
        <p class="card-text"><small class="text-muted">{{$article->pretty_created_at}}</small></p>
    </div>
</div>

Upvotes: 2

D Coder
D Coder

Reputation: 572

here is tutorial for crabon: More

 $dt     = Carbon::now();
 $past   = $dt->subMonth();
 $future = $dt->addMonth();

 echo $dt->subDays(10)->diffForHumans();     // 10 days ago
 echo $dt->diffForHumans($past);             // 1 month ago
  echo $dt->diffForHumans($future);           // 1 month before

Upvotes: 0

Abhishek
Abhishek

Reputation: 3967

$diff = $post->created_at->diffInDays()

$diff = $post->created_at->diffInDays()

Now the logic:

if($diff == 1)
  echo 'today';
elseif($diff >1 && $diff <= 10)
  echo "$diff days ago";
else
  echo $diff->created_at;

Note this is only for your particular situation. Otherwise you should use Carbon' s diffForHumans()

Upvotes: 1

Filip Koblański
Filip Koblański

Reputation: 9988

You can try \Carbon\Carbon class and diff for human like here:

http://carbon.nesbot.com/docs/#api-humandiff

Upvotes: 1

scrubmx
scrubmx

Reputation: 2556

Have you check put the Carbon diff for humans feature?

http://carbon.nesbot.com/docs/#api-humandiff

Since the created_at field is a Carbon instance by default you can call carbon methods on it like so:

$post->created_at->diffForHumans()

Upvotes: 1

Related Questions