Skip to content

Commit f5ae543

Browse files
committed
Return response like with posts.
1 parent 8e12d6a commit f5ae543

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed

app/Http/Resources/Like.php

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
<?php
2+
3+
namespace App\Http\Resources;
4+
5+
use Illuminate\Http\Resources\Json\JsonResource;
6+
use App\Http\Resources\User as UserResource;
7+
8+
class Like extends JsonResource
9+
{
10+
/**
11+
* Transform the resource into an array.
12+
*
13+
* @param \Illuminate\Http\Request $request
14+
* @return array
15+
*/
16+
public function toArray($request)
17+
{
18+
return [
19+
'id' => $this->id,
20+
'like' => $this->like,
21+
'user' => new UserResource($this->user),
22+
'post_id' => $this->post_id,
23+
'created_at' => $this->created_at->diffForHumans(),
24+
'updated_at' => $this->updated_at->diffForHumans(),
25+
];
26+
}
27+
}

app/Http/Resources/Post.php

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
use Illuminate\Http\Resources\Json\JsonResource;
66
use App\Http\Resources\User as UserResource;
77
use App\Http\Resources\Comments as CommentResource;
8+
use App\Http\Resources\Like as LikeResource;
89

910

1011
class Post extends JsonResource
@@ -17,13 +18,20 @@ class Post extends JsonResource
1718
*/
1819
public function toArray($request)
1920
{
21+
// Fetch all comments for specific posts.
2022
$totalCommentPostHas = [];
2123
$totalComments = $this->comments;
22-
2324
foreach($totalComments as $comment) {
2425
array_push($totalCommentPostHas, new CommentResource($comment));
2526
}
2627

28+
// Fetch all like for specific posts.
29+
$totalLikePostHas = [];
30+
$totalLikes = $this->likes;
31+
foreach ($totalLikes as $like) {
32+
array_push($totalLikePostHas, new LikeResource($like));
33+
}
34+
2735
return [
2836
'id' => $this->id,
2937
'title' => $this->title,
@@ -32,6 +40,7 @@ public function toArray($request)
3240
'category' => $this->category,
3341
'user' => new UserResource($this->user),
3442
'comments' => $totalCommentPostHas,
43+
'likes' => $totalLikePostHas,
3544
'created_at' => $this->created_at->diffForHumans(),
3645
'updated_at' => $this->updated_at->diffForHumans(),
3746
];

0 commit comments

Comments
 (0)