validate([ 'content' => 'required|string|max:1000', ]); $model = $this->getModel($type, $id); $this->checkAccess($model); $comment = $model->comments()->create([ 'user_id' => auth()->id(), 'content' => $request->content, ]); return response()->json([ 'message' => 'Comment added successfully', 'comment' => $comment->load('user'), ], 201); } /** * Get all comments for a model */ public function getComments($type, $id) { $model = $this->getModel($type, $id); $this->checkAccess($model); $comments = $model->comments() ->with('user') ->latest() ->paginate(20); return response()->json($comments); } /** * Update comment */ public function updateComment(Request $request, $type, $id, $commentId) { $request->validate([ 'content' => 'required|string|max:1000', ]); $comment = Comment::where('id', $commentId) ->where('user_id', auth()->id()) ->where('commentable_id', $id) ->where('commentable_type', $this->getModelClass($type)) ->firstOrFail(); $comment->update([ 'content' => $request->content, ]); return response()->json([ 'message' => 'Comment updated successfully', 'comment' => $comment->load('user'), ]); } /** * Delete comment */ public function deleteComment($type, $id, $commentId) { $comment = Comment::where('id', $commentId) ->where('user_id', auth()->id()) ->where('commentable_id', $id) ->where('commentable_type', $this->getModelClass($type)) ->firstOrFail(); $comment->delete(); return response()->json([ 'message' => 'Comment deleted successfully', ]); } /** * Get most commented items */ public function mostCommented($type) { $modelClass = $this->getModelClass($type); $userId = auth()->id(); $items = $modelClass::with(['image', 'user']) ->withCount('comments') ->where(function($query) use ($modelClass, $userId) { if (property_exists($modelClass, 'type')) { $query->where('type', 'public') ->orWhere(function($q) use ($userId) { $q->where('type', 'private') ->where('user_id', $userId); }); } }) ->orderBy('comments_count', 'desc') ->limit(10) ->get(); return response()->json($items); } private function getModel($type, $id) { $modelClass = $this->getModelClass($type); $model = $modelClass::findOrFail($id); return $model; } private function getModelClass($type) { $models = [ 'music' => \App\Models\Music::class, 'media' => \App\Models\Media::class, ]; if (!isset($models[$type])) { abort(404, 'Invalid model type'); } return $models[$type]; } private function checkAccess($model) { if (property_exists($model, 'type') && $model->type === 'private') { if (auth()->id() !== $model->user_id) { abort(403, 'You do not have access to this item'); } } } }