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
15 protected $table = 'bookshelves';
17 public $searchFactor = 1.2;
19 protected $fillable = ['name', 'description', 'image_id'];
21 protected $hidden = ['image_id', 'deleted_at'];
24 * Get the books in this shelf.
25 * Should not be used directly since does not take into account permissions.
27 * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
29 public function books()
31 return $this->belongsToMany(Book::class, 'bookshelves_books', 'bookshelf_id', 'book_id')
33 ->orderBy('order', 'asc');
37 * Related books that are visible to the current user.
39 public function visibleBooks(): BelongsToMany
41 return $this->books()->scopes('visible');
45 * Get the url for this bookshelf.
47 public function getUrl(string $path = ''): string
49 return url('/shelves/' . implode('/', [urlencode($this->slug), trim($path, '/')]));
53 * Returns shelf cover image, if cover not exists return default cover image.
55 public function getBookCover(int $width = 440, int $height = 250): string
57 // TODO - Make generic, focused on books right now, Perhaps set-up a better image
58 $default = 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==';
59 if (!$this->image_id || !$this->cover) {
64 return $this->cover->getThumb($width, $height, false) ?? $default;
65 } 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
83 return 'cover_bookshelf';
87 * Check if this shelf contains the given book.
89 public function contains(Book $book): bool
91 return $this->books()->where('id', '=', $book->id)->count() > 0;
95 * Add a book to the end of this shelf.
97 public function appendBook(Book $book)
99 if ($this->contains($book)) {
103 $maxOrder = $this->books()->max('order');
104 $this->books()->attach($book->id, ['order' => $maxOrder + 1]);
108 * Get a visible shelf by its slug.
109 * @throws \Illuminate\Database\Eloquent\ModelNotFoundException
111 public static function getBySlug(string $slug): self
113 return static::visible()->where('slug', '=', $slug)->firstOrFail();