gpt4 book ai didi

php - 拉维尔 5.2 :How to display time like this?

转载 作者:可可西里 更新时间:2023-11-01 00:41:05 25 4
gpt4 key购买 nike

我正在使用 Laravel 5.2,我想这样显示文章的创建时间:

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

怎么做?
提前致谢!

编辑:

Controller :

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

查看:

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

我应该在哪里使用 CarbondiffForHumans()

最佳答案

你可以定义accessor对于自定义属性

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

}

然后在 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>

关于php - 拉维尔 5.2 :How to display time like this?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37103934/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com