- $images = $this->image->where('type', '=', 'gallery');
-
- $page = $this->page->findOrFail($pageId);
-
- if ($filter === 'page') {
- $images = $images->where('uploaded_to', '=', $page->id);
- } elseif ($filter === 'book') {
- $validPageIds = $page->book->pages->pluck('id')->toArray();
- $images = $images->whereIn('uploaded_to', $validPageIds);
+ $contextPage = $this->page->findOrFail($uploadedTo);
+ $parentFilter = null;
+
+ if ($filterType === 'book' || $filterType === 'page') {
+ $parentFilter = function (Builder $query) use ($filterType, $contextPage) {
+ if ($filterType === 'page') {
+ $query->where('uploaded_to', '=', $contextPage->id);
+ } elseif ($filterType === 'book') {
+ $validPageIds = $contextPage->book->pages()->visible()->get(['id'])->pluck('id')->toArray();
+ $query->whereIn('uploaded_to', $validPageIds);
+ }
+ };