From c4abf94c572f5c4d6a65c6be82872ae5b01b68f4 Mon Sep 17 00:00:00 2001 From: AmirmahdiNourkazemi Date: Wed, 26 Nov 2025 10:34:17 +0330 Subject: [PATCH] feat: add tags and filter --- app/Http/Controllers/MediaController.php | 65 +++++++++++++++++++++--- 1 file changed, 58 insertions(+), 7 deletions(-) diff --git a/app/Http/Controllers/MediaController.php b/app/Http/Controllers/MediaController.php index 7d7fda5..612f7f7 100644 --- a/app/Http/Controllers/MediaController.php +++ b/app/Http/Controllers/MediaController.php @@ -73,16 +73,67 @@ public function store(Request $request) } // GET all visible media - public function index() - { - $media = Media::with(['image', 'category', 'myNote' , 'tags']) - ->where('visibility', 'public') - ->orWhere('user_id', auth()->id()) - ->get(); +public function index(Request $request) +{ + $query = Media::with(['image', 'category', 'myNote', 'tags']) + ->where(function($q) { + $q->where('visibility', 'public') + ->orWhere('user_id', auth()->id()); + }); - return response()->json($media); + // ---------------------------- + // Filter by category_id + // ---------------------------- + if ($request->filled('category')) { + $query->where('category_id', $request->category); } + // ---------------------------- + // Filter by tags (multiple) + // ?tags=relax,sleep + // ---------------------------- + if ($request->filled('tags')) { + $tags = explode(',', $request->tags); + + $query->whereHas('tags', function($q) use ($tags) { + $q->whereIn('name', $tags); + }); + } + + // ---------------------------- + // Global search + // ?search=sleep OR ?search=rel + // Search in: title, caption, category name, tags + // ---------------------------- + if ($request->filled('search')) { + $search = $request->search; + + $query->where(function($q) use ($search) { + + // title & caption + $q->where('title', 'LIKE', "%$search%") + ->orWhere('caption', 'LIKE', "%$search%") + + // category (join) + ->orWhereHas('category', function($c) use ($search) { + $c->where('name', 'LIKE', "%$search%"); + }) + + // tags + ->orWhereHas('tags', function($t) use ($search) { + $t->where('name', 'LIKE', "%$search%"); + }); + }); + } + + // ---------------------------- + // Final result + // ---------------------------- + return response()->json( + $query->orderBy('created_at', 'desc')->get() + ); +} + public function show($id) { $media = Media::with(['image', 'category', 'myNote' , 'tags'])