3 namespace BookStack\Entities\Controllers;
5 use BookStack\Entities\Models\Book;
6 use BookStack\Entities\Models\Chapter;
7 use BookStack\Entities\Repos\ChapterRepo;
8 use BookStack\Exceptions\PermissionsException;
9 use BookStack\Http\ApiController;
11 use Illuminate\Database\Eloquent\Relations\HasMany;
12 use Illuminate\Http\Request;
14 class ChapterApiController extends ApiController
18 'book_id' => ['required', 'integer'],
19 'name' => ['required', 'string', 'max:255'],
20 'description' => ['string', 'max:1000'],
24 'book_id' => ['integer'],
25 'name' => ['string', 'min:1', 'max:255'],
26 'description' => ['string', 'max:1000'],
31 public function __construct(
32 protected ChapterRepo $chapterRepo
37 * Get a listing of chapters visible to the user.
39 public function list()
41 $chapters = Chapter::visible();
43 return $this->apiListingResponse($chapters, [
44 'id', 'book_id', 'name', 'slug', 'description', 'priority',
45 'created_at', 'updated_at', 'created_by', 'updated_by', 'owned_by',
50 * Create a new chapter in the system.
52 public function create(Request $request)
54 $requestData = $this->validate($request, $this->rules['create']);
56 $bookId = $request->get('book_id');
57 $book = Book::visible()->findOrFail($bookId);
58 $this->checkOwnablePermission('chapter-create', $book);
60 $chapter = $this->chapterRepo->create($requestData, $book);
62 return response()->json($chapter->load(['tags']));
66 * View the details of a single chapter.
68 public function read(string $id)
70 $chapter = Chapter::visible()->with(['tags', 'createdBy', 'updatedBy', 'ownedBy', 'pages' => function (HasMany $query) {
71 $query->scopes('visible')->get(['id', 'name', 'slug']);
74 return response()->json($chapter);
78 * Update the details of a single chapter.
79 * Providing a 'book_id' property will essentially move the chapter
80 * into that parent element if you have permissions to do so.
82 public function update(Request $request, string $id)
84 $requestData = $this->validate($request, $this->rules()['update']);
85 $chapter = Chapter::visible()->findOrFail($id);
86 $this->checkOwnablePermission('chapter-update', $chapter);
88 if ($request->has('book_id') && $chapter->book_id !== intval($requestData['book_id'])) {
89 $this->checkOwnablePermission('chapter-delete', $chapter);
92 $this->chapterRepo->move($chapter, "book:{$requestData['book_id']}");
93 } catch (Exception $exception) {
94 if ($exception instanceof PermissionsException) {
95 $this->showPermissionError();
98 return $this->jsonError(trans('errors.selected_book_not_found'));
102 $updatedChapter = $this->chapterRepo->update($chapter, $requestData);
104 return response()->json($updatedChapter->load(['tags']));
109 * This will typically send the chapter to the recycle bin.
111 public function delete(string $id)
113 $chapter = Chapter::visible()->findOrFail($id);
114 $this->checkOwnablePermission('chapter-delete', $chapter);
116 $this->chapterRepo->destroy($chapter);
118 return response('', 204);