feat: add tags and filter
This commit is contained in:
@@ -73,14 +73,65 @@ public function store(Request $request)
|
|||||||
}
|
}
|
||||||
|
|
||||||
// GET all visible media
|
// GET all visible media
|
||||||
public function index()
|
public function index(Request $request)
|
||||||
{
|
{
|
||||||
$media = Media::with(['image', 'category', 'myNote' , 'tags'])
|
$query = Media::with(['image', 'category', 'myNote', 'tags'])
|
||||||
->where('visibility', 'public')
|
->where(function($q) {
|
||||||
->orWhere('user_id', auth()->id())
|
$q->where('visibility', 'public')
|
||||||
->get();
|
->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)
|
public function show($id)
|
||||||
|
|||||||
Reference in New Issue
Block a user