2013-06-12 32 views
3

我正在使我的網站在Laravel 4中,並且我在表中有created_at & updated_at字段。我想製作一個新聞系統,讓我知道自發布後已經過了多少時間。如何在laravel 4中發佈(時間)

| name | text |  created_at  |  updated_at  | 
| __________ | __________ | ________________________ | ___________________ | 
| news name | news_text | 2013-06-12 11:53:25 | 2013-06-12 11:53:25 | 

我想說明是這樣的:

-created 5分鐘前

-created 4個月前

如果郵政是老年人超過1個月

-created at 2012年11月5日

+2

酷的故事。到目前爲止你做了什麼? – Jessica

回答

11

嘗試使用Carbon。 Laravel已經將它作爲依賴項,所以不需要添加它。

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(); 
} 

按照要求,我會充分整合,對我怎麼覺得這是更好的方式來做到這一點的例子。首先,我假設我可能會在幾個不同的地方和幾種不同的視圖中使用它,所以最好的做法是將這些代碼放入模型中,以便您可以方便地從任何地方調用它,而不會有任何麻煩。

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(); 
     } 
    } 

} 

然後,在視圖文件,你根本就$news->formattedCreatedDate()。例如:

<div class="post"> 
    <h1 class="title">{{ $news->title }}</h1> 
    <span class="date">{{ $news->forammatedCreatedDate() }}</span> 
    <p class="content">{{ $news->content }}</p> 
</div> 
+0

你能否更充實地回答這個問題,以表明你將如何將它融入到視圖層面? –

+0

你的願望是我的命令。 – rmobis

+0

爲我工作。謝謝 – Foxinni

4

要求碳:

use Carbon\Carbon; 

並使用它:

$user = User::find(2); 

echo $user->created_at->diffForHumans(Carbon::now()); 

你應該得到這樣的:

19 days before 
+0

我不相信你必須通過'Carbon :: now()' –