3 namespace BookStack\Entities\Models;
5 use BookStack\Uploads\Image;
6 use Illuminate\Database\Eloquent\Factories\HasFactory;
7 use Illuminate\Database\Eloquent\Relations\BelongsTo;
8 use Illuminate\Database\Eloquent\Relations\BelongsToMany;
10 class Bookshelf extends Entity implements HasCoverImage
14 protected $table = 'bookshelves';
16 public $searchFactor = 1.2;
18 protected $fillable = ['name', 'description', 'image_id'];
20 protected $hidden = ['restricted', 'image_id', 'deleted_at'];
23 * Get the books in this shelf.
24 * Should not be used directly since does not take into account permissions.
26 * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
28 public function books()
30 return $this->belongsToMany(Book::class, 'bookshelves_books', 'bookshelf_id', 'book_id')
32 ->orderBy('order', 'asc');
36 * Related books that are visible to the current user.
38 public function visibleBooks(): BelongsToMany
40 return $this->books()->scopes('visible');
44 * Get the url for this bookshelf.
46 public function getUrl(string $path = ''): string
48 return url('/shelves/' . implode('/', [urlencode($this->slug), trim($path, '/')]));
52 * Returns BookShelf cover image, if cover does not exists return default cover image.
54 * @param int $width - Width of the image
55 * @param int $height - Height of the image
59 public function getBookCover($width = 440, $height = 250)
61 // TODO - Make generic, focused on books right now, Perhaps set-up a better image
62 $default = 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==';
63 if (!$this->image_id) {
68 $cover = $this->cover ? url($this->cover->getThumb($width, $height, false)) : $default;
69 } catch (\Exception $err) {
77 * Get the cover image of the shelf.
79 public function cover(): BelongsTo
81 return $this->belongsTo(Image::class, 'image_id');
85 * Get the type of the image model that is used when storing a cover image.
87 public function coverImageTypeKey(): string
89 return 'cover_bookshelf';
93 * Check if this shelf contains the given book.
95 public function contains(Book $book): bool
97 return $this->books()->where('id', '=', $book->id)->count() > 0;
101 * Add a book to the end of this shelf.
103 public function appendBook(Book $book)
105 if ($this->contains($book)) {
109 $maxOrder = $this->books()->max('order');
110 $this->books()->attach($book->id, ['order' => $maxOrder + 1]);