- $sortedBooks = [];
- $updatedModels = collect();
- $sortMap = json_decode($request->get('sort-tree'));
- $defaultBookId = $book->id;
+ $sortMap = collect(json_decode($request->get('sort-tree')));
+ $bookIdsInvolved = collect([$book->id]);
+
+ // Load models into map
+ $sortMap->each(function ($mapItem) use ($bookIdsInvolved) {
+ $mapItem->type = ($mapItem->type === 'page' ? 'page' : 'chapter');
+ $mapItem->model = $this->entityRepo->getById($mapItem->type, $mapItem->id);
+ // Store source and target books
+ $bookIdsInvolved->push(intval($mapItem->model->book_id));
+ $bookIdsInvolved->push(intval($mapItem->book));
+ });
+
+ // Get the books involved in the sort
+ $bookIdsInvolved = $bookIdsInvolved->unique()->toArray();
+ $booksInvolved = $this->entityRepo->book->newQuery()->whereIn('id', $bookIdsInvolved)->get();
+ // Throw permission error if invalid ids or inaccessible books given.
+ if (count($bookIdsInvolved) !== count($booksInvolved)) {
+ $this->showPermissionError();
+ }
+ // Check permissions of involved books
+ $booksInvolved->each(function (Book $book) {
+ $this->checkOwnablePermission('book-update', $book);
+ });