has('tag')) { $tag = $normalize($request->tag); $query->whereHas('tags', function ($q) use ($tag) { $q->whereRaw("REPLACE(name, '‌', ' ') LIKE ?", ["%{$tag}%"]); }); } if ($request->has('category')) { $category = $normalize($request->category); $query->whereHas('category', function ($q) use ($category) { $q->whereRaw("REPLACE(name, '‌', ' ') LIKE ?", ["%{$category}%"]); }); } return response()->json($query->get()); } /** * Store a newly created resource in storage. */ public function store(Request $request) { $data = $request->validate([ 'title' => 'required|string', 'category' => 'nullable|string', 'tags' => 'nullable|array', 'tags.*' => 'string' ]); $category = null; if (!empty($data['category'])) { $category = Category::firstOrCreate(['name' => $data['category']]); } $question = Question::create([ 'title' => $data['title'], 'category_id' => $category?->id ]); if (!empty($data['tags'])) { $tagIds = []; foreach ($data['tags'] as $tagName) { $tag = Tag::firstOrCreate(['name' => $tagName]); $tagIds[] = $tag->id; } $question->tags()->sync($tagIds); } return response()->json($question->load(['tags', 'category']), 201); } /** * Display the specified resource. */ public function show(Question $question) { return response()->json($question->load(['tags', 'category'])); } /** * Update the specified resource in storage. */ public function update(Request $request, Question $question) { $data = $request->validate([ 'title' => 'sometimes|string', 'category' => 'nullable|string', 'tags' => 'nullable|array', 'tags.*' => 'string' ]); if (isset($data['title'])) { $question->update(['title' => $data['title']]); } if (array_key_exists('category', $data)) { if ($data['category']) { $category = Category::firstOrCreate(['name' => $data['category']]); $question->update(['category_id' => $category->id]); } else { $question->update(['category_id' => null]); } } if (isset($data['tags'])) { $tagIds = []; foreach ($data['tags'] as $tagName) { $tag = Tag::firstOrCreate(['name' => $tagName]); $tagIds[] = $tag->id; } $question->tags()->sync($tagIds); } return response()->json($question->load(['tags', 'category'])); } /** * Remove the specified resource from storage. */ public function destroy(Question $question) { $question->delete(); return response()->json(['message' => 'سوال حذف شد']); } }