3 namespace BookStack\Http\Controllers\Api;
5 use BookStack\Entities\Models\Bookshelf;
6 use BookStack\Entities\Repos\BookshelfRepo;
8 use Illuminate\Database\Eloquent\Relations\BelongsToMany;
9 use Illuminate\Http\Request;
10 use Illuminate\Validation\ValidationException;
12 class BookshelfApiController extends ApiController
14 protected BookshelfRepo $bookshelfRepo;
17 * BookshelfApiController constructor.
19 public function __construct(BookshelfRepo $bookshelfRepo)
21 $this->bookshelfRepo = $bookshelfRepo;
25 * Get a listing of shelves visible to the user.
27 public function list()
29 $shelves = Bookshelf::visible();
31 return $this->apiListingResponse($shelves, [
32 'id', 'name', 'slug', 'description', 'created_at', 'updated_at', 'created_by', 'updated_by', 'owned_by',
37 * Create a new shelf in the system.
38 * An array of books IDs can be provided in the request. These
39 * will be added to the shelf in the same order as provided.
41 * @throws ValidationException
43 public function create(Request $request)
45 $this->checkPermission('bookshelf-create-all');
46 $requestData = $this->validate($request, $this->rules['create']);
48 $bookIds = $request->get('books', []);
49 $shelf = $this->bookshelfRepo->create($requestData, $bookIds);
51 return response()->json($shelf);
55 * View the details of a single shelf.
57 public function read(string $id)
59 $shelf = Bookshelf::visible()->with([
60 'tags', 'cover', 'createdBy', 'updatedBy', 'ownedBy',
61 'books' => function (BelongsToMany $query) {
62 $query->scopes('visible')->get(['id', 'name', 'slug']);
66 return response()->json($shelf);
70 * Update the details of a single shelf.
71 * An array of books IDs can be provided in the request. These
72 * will be added to the shelf in the same order as provided and overwrite
73 * any existing book assignments.
75 * @throws ValidationException
77 public function update(Request $request, string $id)
79 $shelf = Bookshelf::visible()->findOrFail($id);
80 $this->checkOwnablePermission('bookshelf-update', $shelf);
82 $requestData = $this->validate($request, $this->rules['update']);
83 $bookIds = $request->get('books', null);
85 $shelf = $this->bookshelfRepo->update($shelf, $requestData, $bookIds);
87 return response()->json($shelf);
91 * Delete a single shelf.
92 * This will typically send the shelf to the recycle bin.
96 public function delete(string $id)
98 $shelf = Bookshelf::visible()->findOrFail($id);
99 $this->checkOwnablePermission('bookshelf-delete', $shelf);
101 $this->bookshelfRepo->destroy($shelf);
103 return response('', 204);
106 protected function rules(): array
110 'name' => ['required', 'string', 'max:255'],
111 'description' => ['string', 'max:1000'],
112 'books' => ['array'],
114 'image' => array_merge(['nullable'], $this->getImageValidationRules()),
117 'name' => ['string', 'min:1', 'max:255'],
118 'description' => ['string', 'max:1000'],
119 'books' => ['array'],
121 'image' => array_merge(['nullable'], $this->getImageValidationRules()),