3 namespace BookStack\Entities\Models;
5 use BookStack\Uploads\Image;
7 use Illuminate\Database\Eloquent\Factories\HasFactory;
8 use Illuminate\Database\Eloquent\Relations\BelongsTo;
9 use Illuminate\Database\Eloquent\Relations\BelongsToMany;
11 class Bookshelf extends Entity implements HasCoverImage
14 use HasHtmlDescription;
16 protected $table = 'bookshelves';
18 public float $searchFactor = 1.2;
20 protected $fillable = ['name', 'description', 'image_id'];
22 protected $hidden = ['image_id', 'deleted_at'];
25 * Get the books in this shelf.
26 * Should not be used directly since does not take into account permissions.
28 * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
30 public function books()
32 return $this->belongsToMany(Book::class, 'bookshelves_books', 'bookshelf_id', 'book_id')
34 ->orderBy('order', 'asc');
38 * Related books that are visible to the current user.
40 public function visibleBooks(): BelongsToMany
42 return $this->books()->scopes('visible');
46 * Get the url for this bookshelf.
48 public function getUrl(string $path = ''): string
50 return url('/shelves/' . implode('/', [urlencode($this->slug), trim($path, '/')]));
54 * Returns shelf cover image, if cover not exists return default cover image.
56 public function getBookCover(int $width = 440, int $height = 250): string
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 || !$this->cover) {
65 return $this->cover->getThumb($width, $height, false) ?? $default;
66 } catch (Exception $err) {
72 * Get the cover image of the shelf.
74 public function cover(): BelongsTo
76 return $this->belongsTo(Image::class, 'image_id');
80 * Get the type of the image model that is used when storing a cover image.
82 public function coverImageTypeKey(): string
84 return 'cover_bookshelf';
88 * Check if this shelf contains the given book.
90 public function contains(Book $book): bool
92 return $this->books()->where('id', '=', $book->id)->count() > 0;
96 * Add a book to the end of this shelf.
98 public function appendBook(Book $book)
100 if ($this->contains($book)) {
104 $maxOrder = $this->books()->max('order');
105 $this->books()->attach($book->id, ['order' => $maxOrder + 1]);
109 * Get a visible shelf by its slug.
110 * @throws \Illuminate\Database\Eloquent\ModelNotFoundException
112 public static function getBySlug(string $slug): self
114 return static::visible()->where('slug', '=', $slug)->firstOrFail();