与时间戳相关的 IF 语句

IF statement relating to timestamps

我正在使用 foreach 检索评论,我正在尝试在 if 语句中编写代码,声明如果时间戳 created_at 和 updated_at 相等,那么我将只显示创建于时间戳,但如果它们不同,我想同时显示两者。我该怎么做?到目前为止,我有这个抛出错误告诉我他们是 if 语句的错误...

型号:

 public function comments()
    {
        return $this->hasMany('App\Comment','batsmen_id')->orderBy('created_at', 'DESC');
    }

控制器:

public function getSingle($slug)
{
    //fetch from the database based on slug.
    $batsmen = Batsmen::with('comments')->where('slug', '=', $slug)->first();


    //return view
    return view('batsmen.single')->withBatsmen($batsmen);

}

查看:

@foreach($batsmen->comments as $comments)
@if($comments->created_at = $comments->updated_at)
Posted at {{$comments->created_at}}
@else
Posted at {{$comments->created_at}}
Updated at {{$comments->updated_at}}

@endIf

@if($comments->created_at = $comments->updated_at)

这是不正确的,单个等号是赋值运算符。要与 vales 进行比较,您需要使用 =====.

== 比较两个值,而 === 比较值和类型。

Laravel 在整个框架中使用 Carbon 库来处理日期。它有一些有用的辅助函数,用于比较许多不同格式的日期,为您节省一些跑腿工作。

Carbon::parse($date1)->eq(Carbon::parse($date2))

会告诉你两个日期是否相等。

如果你已经有了碳对象,你就可以做

$comments->created_at->eq( $comments->updated_at);