paginate(10); return CategoryResource::collection($categories); } // نمایش یک دسته‌بندی خاص public function show($id) { $category = Category::with('posts')->findOrFail($id); return new CategoryResource($category); } /** * نمایش دسته‌بندی و پست‌های مرتبط با آن بر اساس slug * * @param \Illuminate\Http\Request $request * @param string $slug * @return \Illuminate\Http\JsonResponse */ public function getCategoryWithPosts(Request $request, $slug) { // یافتن دسته‌بندی بر اساس slug $category = Category::where('slug', $slug)->first(); if (!$category) { return response()->json([ 'message' => 'دسته‌بندی مورد نظر یافت نشد.' ], 404); } // دریافت تعداد پست‌ها در هر صفحه (پیش‌فرض: ۱۰) $perPage = $request->input('per_page', 10); // دریافت پست‌های مربوط به این دسته‌بندی به ترتیب جدیدترین‌ها $posts = $category->posts()->with(['category', 'tags', 'author']) ->orderBy('published_at', 'desc') ->paginate($perPage); // بازگشت اطلاعات دسته‌بندی و پست‌ها return response()->json([ 'category' => new CategoryResource($category), 'posts' => PostResource::collection($posts), 'pagination' => [ 'total' => $posts->total(), 'per_page' => $posts->perPage(), 'current_page' => $posts->currentPage(), 'last_page' => $posts->lastPage(), 'from' => $posts->firstItem(), 'to' => $posts->lastItem(), ], ], 200); } // ذخیره یک دسته‌بندی جدید public function store(Request $request) { $validator = Validator::make($request->all(), [ 'name' => 'required|string|max:255|unique:categories,name', 'slug' => 'required|string|unique:categories,slug', 'description' => 'required|string', 'short_description' => 'nullable|string|max:500', 'image' => 'nullable|url', ]); if ($validator->fails()) { return response()->json($validator->errors(), 422); } $category = Category::create($validator->validated()); return new CategoryResource($category); } // به‌روزرسانی یک دسته‌بندی خاص public function update(Request $request, $id) { $category = Category::findOrFail($id); $validator = Validator::make($request->all(), [ 'name' => 'sometimes|required|string|max:255|unique:categories,name,' . $category->id, 'slug' => 'sometimes|required|string|unique:categories,slug,' . $category->id, 'description' => 'sometimes|required|string', 'short_description' => 'nullable|string|max:500', 'image' => 'nullable|url', ]); if ($validator->fails()) { return response()->json($validator->errors(), 422); } $category->update($validator->validated()); return new CategoryResource($category); } // حذف یک دسته‌بندی خاص public function destroy($id) { $category = Category::findOrFail($id); // قبل از حذف، مطمئن شوید که پست‌ها به دسته‌بندی دیگری منتقل شده‌اند یا حذف شوند // برای سادگی، اینجا فقط دسته‌بندی را حذف می‌کنیم $category->delete(); return response()->json(['message' => 'Category deleted successfully'], 200); } }