Skip to main content

Black Friday 2025! Only until December 1st: coupon FRIDAY25 for 40% off Yearly/Lifetime membership!

Read more here

guillaumebriday/laravel-blog

1797 stars
4 code files
View guillaumebriday/laravel-blog on GitHub

app/Http/Controllers/Api/V1/CommentController.php

Open in GitHub
use App\Models\Post;
use App\Http\Resources\Comment as CommentResource;
 
class PostCommentController extends Controller
{
public function index(Request $request, Post $post): ResourceCollection
{
return CommentResource::collection(
$post->comments()->with('author')->latest()->paginate($request->input('limit', 20))
);
}
//
}

resources/js/components/comments/CommentList.vue

Open in GitHub
<template>
<div>
<comment
v-for="comment in comments"
:key="comment.id"
:comment="comment"
:data-confirm="dataConfirm"
@deleted="removeComment(comment)"
/>
//
</div>
</template>
 
<script>
//
data () {
return {
comments: [],
isLoading: false,
endpoint: `/api/v1/posts/${this.postId}/comments/`
}
},
mounted () {
this.retrieveComments()
Event.$on('added', comment => this.addComment(comment))
window.Echo.channel(`post.${this.postId}`)
.listen('.comment.posted', e => this.addComment(e.comment))
},
methods: {
retrieveComments () {
this.isLoading = true
axios.get(this.endpoint).then(({ data }) => {
this.comments.push(...data.data)
this.isLoading = false
this.endpoint = data.links.next
})
},
}
//
}
</script>

routes/api.php

Open in GitHub
use Illuminate\Support\Facades\Route;
 
Route::prefix('v1')->namespace('Api\V1')->group(function () {
//
Route::apiResource('posts.comments', 'PostCommentController')->only('index');
//
});

app/Http/Resources/Comment.php

Open in GitHub
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Facades\Auth;
 
class Comment extends JsonResource
{
/**
* Transform the resource into an array.
*/
public function toArray($request): array
{
$user = Auth::guard('api')->user();
 
return [
'id' => $this->id,
'content' => $this->content,
'posted_at' => $this->posted_at->toIso8601String(),
'humanized_posted_at' => humanize_date($this->posted_at),
'author_id' => $this->author_id,
'post_id' => $this->post_id,
'author_name' => $this->author->name,
'author_url' => route('users.show', $this->author),
'can_delete' => $user ? $user->can('delete', $this->resource) : false
];
}
}

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.