3 namespace BookStack\Entities\Models;
5 use BookStack\Uploads\Image;
6 use Illuminate\Database\Eloquent\Relations\BelongsTo;
7 use Illuminate\Database\Eloquent\Relations\BelongsToMany;
9 class Bookshelf extends Entity implements HasCoverImage
11 protected $table = 'bookshelves';
13 public $searchFactor = 3;
15 protected $fillable = ['name', 'description', 'image_id'];
17 protected $hidden = ['restricted', 'image_id', 'deleted_at'];
20 * Get the books in this shelf.
21 * Should not be used directly since does not take into account permissions.
23 * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
25 public function books()
27 return $this->belongsToMany(Book::class, 'bookshelves_books', 'bookshelf_id', 'book_id')
29 ->orderBy('order', 'asc');
33 * Related books that are visible to the current user.
35 public function visibleBooks(): BelongsToMany
37 return $this->books()->visible();
41 * Get the url for this bookshelf.
43 public function getUrl(string $path = ''): string
45 return url('/shelves/' . implode('/', [urlencode($this->slug), trim($path, '/')]));
49 * Returns BookShelf cover image, if cover does not exists return default cover image.
51 * @param int $width - Width of the image
52 * @param int $height - Height of the image
56 public function getBookCover($width = 440, $height = 250)
58 // TODO - Make generic, focused on books right now, Perhaps set-up a better image
59 $default = 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==';
60 if (!$this->image_id) {
65 $cover = $this->cover ? url($this->cover->getThumb($width, $height, false)) : $default;
66 } catch (\Exception $err) {
74 * Get the cover image of the shelf.
76 public function cover(): BelongsTo
78 return $this->belongsTo(Image::class, 'image_id');
82 * Get the type of the image model that is used when storing a cover image.
84 public function coverImageTypeKey(): string
90 * Check if this shelf contains the given book.
96 public function contains(Book $book): bool
98 return $this->books()->where('id', '=', $book->id)->count() > 0;
102 * Add a book to the end of this shelf.
106 public function appendBook(Book $book)
108 if ($this->contains($book)) {
112 $maxOrder = $this->books()->max('order');
113 $this->books()->attach($book->id, ['order' => $maxOrder + 1]);