1 <?php namespace BookStack\Entities\Models;
3 use BookStack\Uploads\Image;
4 use Illuminate\Database\Eloquent\Collection;
5 use Illuminate\Database\Eloquent\Relations\BelongsTo;
6 use Illuminate\Database\Eloquent\Relations\BelongsToMany;
8 class Bookshelf extends Entity implements HasCoverImage
10 protected $table = 'bookshelves';
12 public $searchFactor = 3;
14 protected $fillable = ['name', 'description', 'image_id'];
16 protected $hidden = ['restricted', 'image_id', 'deleted_at'];
19 * Get the books in this shelf.
20 * Should not be used directly since does not take into account permissions.
21 * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
23 public function books()
25 return $this->belongsToMany(Book::class, 'bookshelves_books', 'bookshelf_id', 'book_id')
27 ->orderBy('order', 'asc');
31 * Related books that are visible to the current user.
33 public function visibleBooks(): BelongsToMany
35 return $this->books()->visible();
39 * Get the books in this shelf that are visible to the current user with sorted by custom parameter
40 * @param string $sort - Chosen Column to be sorted
41 * @param string $order - Order of the sort
44 public function visibleBooksByCustomSorting(string $sort = 'name', string $order = 'asc'): Collection
46 return $this->belongsToMany(Book::class, 'bookshelves_books', 'bookshelf_id', 'book_id')
47 ->orderBy($sort, $order)
53 * Get the url for this bookshelf.
55 public function getUrl(string $path = ''): string
57 return url('/shelves/' . implode('/', [urlencode($this->slug), trim($path, '/')]));
61 * Returns BookShelf cover image, if cover does not exists return default cover image.
62 * @param int $width - Width of the image
63 * @param int $height - Height of the image
66 public function getBookCover($width = 440, $height = 250)
68 // TODO - Make generic, focused on books right now, Perhaps set-up a better image
69 $default = 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==';
70 if (!$this->image_id) {
75 $cover = $this->cover ? url($this->cover->getThumb($width, $height, false)) : $default;
76 } catch (\Exception $err) {
83 * Get the cover image of the shelf
85 public function cover(): BelongsTo
87 return $this->belongsTo(Image::class, 'image_id');
91 * Get the type of the image model that is used when storing a cover image.
93 public function coverImageTypeKey(): string
99 * Check if this shelf contains the given book.
103 public function contains(Book $book): bool
105 return $this->books()->where('id', '=', $book->id)->count() > 0;
109 * Add a book to the end of this shelf.
112 public function appendBook(Book $book)
114 if ($this->contains($book)) {
118 $maxOrder = $this->books()->max('order');
119 $this->books()->attach($book->id, ['order' => $maxOrder + 1]);