feat: add tags and filter

This commit is contained in:
2025-11-26 10:34:17 +03:30
parent bebf685f32
commit c4abf94c57
+58 -7
View File
@@ -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'])