-
app/Http/Controllers/Api/V1/CommentController.php
Open in GitHubuse 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 GitHubuse 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 GitHubuse 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 ]; } }