From 6364790b0329868bd02e2f7c07c38a56132100de Mon Sep 17 00:00:00 2001 From: Nafies Luthfi Date: Sun, 5 Aug 2018 21:03:20 +0800 Subject: [PATCH] Add comment time_display attribute Comment time will shown in diffForHumans if created today Comment time will shown in date time yesterday or before Add Comment model test --- app/Entities/Projects/Comment.php | 9 ++++++ .../projects/partials/comment-section.blade.php | 2 +- tests/Unit/Models/CommentTest.php | 32 ++++++++++++++++++++++ 3 files changed, 42 insertions(+), 1 deletion(-) create mode 100644 tests/Unit/Models/CommentTest.php diff --git a/app/Entities/Projects/Comment.php b/app/Entities/Projects/Comment.php index 0ef6df2..f73f6e4 100644 --- a/app/Entities/Projects/Comment.php +++ b/app/Entities/Projects/Comment.php @@ -13,4 +13,13 @@ class Comment extends Model { return $this->belongsTo(User::class); } + + public function getTimeDisplayAttribute() + { + if (now()->format('Y-m-d') != $this->created_at->format('Y-m-d')) { + return $this->created_at; + } + + return $this->created_at->diffForHumans(); + } } diff --git a/resources/views/projects/partials/comment-section.blade.php b/resources/views/projects/partials/comment-section.blade.php index 35e7023..6e70f51 100644 --- a/resources/views/projects/partials/comment-section.blade.php +++ b/resources/views/projects/partials/comment-section.blade.php @@ -11,7 +11,7 @@ @foreach($comments as $comment)
- {{ $comment->created_at }} + {{ $comment->time_display }} {{ $comment->creator->name }}
diff --git a/tests/Unit/Models/CommentTest.php b/tests/Unit/Models/CommentTest.php new file mode 100644 index 0000000..5673997 --- /dev/null +++ b/tests/Unit/Models/CommentTest.php @@ -0,0 +1,32 @@ +make(); + + $this->assertInstanceOf(User::class, $comment->creator); + $this->assertEquals($comment->creator_id, $comment->creator->id); + } + + /** @test */ + public function a_comment_has_time_display_attribute() + { + $comment = factory(Comment::class)->create(['created_at' => now()->subHour()]); + $this->assertEquals($comment->created_at->diffForHumans(), $comment->time_display); + + $comment = factory(Comment::class)->create(['created_at' => now()->subDays(3)]); + $this->assertEquals($comment->created_at, $comment->time_display); + } +}