1 <?php namespace BookStack\Http\Controllers\Api;
3 use BookStack\Facades\Activity;
4 use BookStack\Entities\Repos\BookshelfRepo;
5 use BookStack\Entities\Bookshelf;
7 use Illuminate\Database\Eloquent\Relations\BelongsToMany;
8 use Illuminate\Http\Request;
9 use Illuminate\Validation\ValidationException;
11 class BookshelfApiController extends ApiController
17 protected $bookshelfRepo;
21 'name' => 'required|string|max:255',
22 'description' => 'string|max:1000',
26 'name' => 'string|min:1|max:255',
27 'description' => 'string|max:1000',
33 * BookshelfApiController constructor.
34 * @param BookshelfRepo $bookshelfRepo
36 public function __construct(BookshelfRepo $bookshelfRepo)
38 $this->bookshelfRepo = $bookshelfRepo;
42 * Get a listing of shelves visible to the user.
44 public function list()
46 $shelves = Bookshelf::visible();
47 return $this->apiListingResponse($shelves, [
48 'id', 'name', 'slug', 'description', 'created_at', 'updated_at', 'created_by', 'updated_by', 'image_id',
53 * Create a new shelf in the system.
54 * An array of books IDs can be provided in the request. These
55 * will be added to the shelf in the same order as provided.
56 * @throws ValidationException
58 public function create(Request $request)
60 $this->checkPermission('bookshelf-create-all');
61 $requestData = $this->validate($request, $this->rules['create']);
63 $bookIds = $request->get('books', []);
64 $shelf = $this->bookshelfRepo->create($requestData, $bookIds);
66 Activity::add($shelf, 'bookshelf_create', $shelf->id);
67 return response()->json($shelf);
71 * View the details of a single shelf.
73 public function read(string $id)
75 $shelf = Bookshelf::visible()->with([
76 'tags', 'cover', 'createdBy', 'updatedBy',
77 'books' => function (BelongsToMany $query) {
78 $query->visible()->get(['id', 'name', 'slug']);
81 return response()->json($shelf);
85 * Update the details of a single shelf.
86 * An array of books IDs can be provided in the request. These
87 * will be added to the shelf in the same order as provided and overwrite
88 * any existing book assignments.
89 * @throws ValidationException
91 public function update(Request $request, string $id)
93 $shelf = Bookshelf::visible()->findOrFail($id);
94 $this->checkOwnablePermission('bookshelf-update', $shelf);
96 $requestData = $this->validate($request, $this->rules['update']);
98 $bookIds = $request->get('books', null);
100 $shelf = $this->bookshelfRepo->update($shelf, $requestData, $bookIds);
101 Activity::add($shelf, 'bookshelf_update', $shelf->id);
103 return response()->json($shelf);
109 * Delete a single shelf from the system.
112 public function delete(string $id)
114 $shelf = Bookshelf::visible()->findOrFail($id);
115 $this->checkOwnablePermission('bookshelf-delete', $shelf);
117 $this->bookshelfRepo->destroy($shelf);
118 Activity::addMessage('bookshelf_delete', $shelf->name);
120 return response('', 204);