1 <?php namespace BookStack\Entities;
3 use BookStack\Uploads\Image;
4 use Illuminate\Database\Eloquent\Relations\BelongsTo;
5 use Illuminate\Database\Eloquent\Relations\BelongsToMany;
7 class Bookshelf extends Entity implements HasCoverImage
9 protected $table = 'bookshelves';
11 public $searchFactor = 3;
13 protected $fillable = ['name', 'description', 'image_id'];
16 * Get the books in this shelf.
17 * Should not be used directly since does not take into account permissions.
18 * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
20 public function books()
22 return $this->belongsToMany(Book::class, 'bookshelves_books', 'bookshelf_id', 'book_id')
24 ->orderBy('order', 'asc');
28 * Related books that are visible to the current user.
30 public function visibleBooks(): BelongsToMany
32 return $this->books()->visible();
36 * Get the url for this bookshelf.
37 * @param string|bool $path
40 public function getUrl($path = false)
42 if ($path !== false) {
43 return url('/shelves/' . urlencode($this->slug) . '/' . trim($path, '/'));
45 return url('/shelves/' . urlencode($this->slug));
49 * Returns BookShelf cover image, if cover does not exists return default cover image.
50 * @param int $width - Width of the image
51 * @param int $height - Height of the image
54 public function getBookCover($width = 440, $height = 250)
56 // TODO - Make generic, focused on books right now, Perhaps set-up a better image
57 $default = 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==';
58 if (!$this->image_id) {
63 $cover = $this->cover ? url($this->cover->getThumb($width, $height, false)) : $default;
64 } catch (\Exception $err) {
71 * Get the cover image of the shelf
73 public function cover(): BelongsTo
75 return $this->belongsTo(Image::class, 'image_id');
79 * Get the type of the image model that is used when storing a cover image.
81 public function coverImageTypeKey(): string
87 * Get an excerpt of this book's description to the specified length or less.
91 public function getExcerpt(int $length = 100)
93 $description = $this->description;
94 return mb_strlen($description) > $length ? mb_substr($description, 0, $length-3) . '...' : $description;
98 * Check if this shelf contains the given book.
102 public function contains(Book $book): bool
104 return $this->books()->where('id', '=', $book->id)->count() > 0;
108 * Add a book to the end of this shelf.
111 public function appendBook(Book $book)
113 if ($this->contains($book)) {
117 $maxOrder = $this->books()->max('order');
118 $this->books()->attach($book->id, ['order' => $maxOrder + 1]);