1 <?php namespace BookStack\Http\Controllers\Api;
3 use BookStack\Entities\Book;
4 use BookStack\Entities\Chapter;
5 use BookStack\Entities\Repos\ChapterRepo;
6 use BookStack\Facades\Activity;
7 use Illuminate\Database\Eloquent\Relations\HasMany;
8 use Illuminate\Http\Request;
10 class ChapterApiController extends ApiController
12 protected $chapterRepo;
16 'book_id' => 'required|integer',
17 'name' => 'required|string|max:255',
18 'description' => 'string|max:1000',
22 'book_id' => 'integer',
23 'name' => 'string|min:1|max:255',
24 'description' => 'string|max:1000',
30 * ChapterController constructor.
32 public function __construct(ChapterRepo $chapterRepo)
34 $this->chapterRepo = $chapterRepo;
38 * Get a listing of chapters visible to the user.
40 public function list()
42 $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',
50 * Create a new chapter in the system.
52 public function create(Request $request)
54 $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($request->all(), $book);
61 Activity::add($chapter, 'chapter_create', $book->id);
63 return response()->json($chapter->load(['tags']));
67 * View the details of a single chapter.
69 public function read(string $id)
71 $chapter = Chapter::visible()->with(['tags', 'createdBy', 'updatedBy', 'pages' => function (HasMany $query) {
72 $query->visible()->get(['id', 'name', 'slug']);
74 return response()->json($chapter);
78 * Update the details of a single chapter.
80 public function update(Request $request, string $id)
82 $chapter = Chapter::visible()->findOrFail($id);
83 $this->checkOwnablePermission('chapter-update', $chapter);
85 $updatedChapter = $this->chapterRepo->update($chapter, $request->all());
86 Activity::add($chapter, 'chapter_update', $chapter->book->id);
88 return response()->json($updatedChapter->load(['tags']));
92 * Delete a chapter from the system.
94 public function delete(string $id)
96 $chapter = Chapter::visible()->findOrFail($id);
97 $this->checkOwnablePermission('chapter-delete', $chapter);
99 $this->chapterRepo->destroy($chapter);
100 Activity::addMessage('chapter_delete', $chapter->name, $chapter->book->id);
102 return response('', 204);