1 <?php namespace BookStack\Entities\Models;
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'];
15 protected $hidden = ['restricted', 'image_id', 'deleted_at'];
18 * Get the books in this shelf.
19 * Should not be used directly since does not take into account permissions.
20 * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
22 public function books()
24 return $this->belongsToMany(Book::class, 'bookshelves_books', 'bookshelf_id', 'book_id')
26 ->orderBy('order', 'asc');
30 * Related books that are visible to the current user.
32 public function visibleBooks(): BelongsToMany
34 return $this->books()->visible();
38 * Get the url for this bookshelf.
40 public function getUrl(string $path = ''): string
42 return url('/shelves/' . implode('/', [urlencode($this->slug), trim($path, '/')]));
46 * Returns BookShelf cover image, if cover does not exists return default cover image.
47 * @param int $width - Width of the image
48 * @param int $height - Height of the image
51 public function getBookCover($width = 440, $height = 250)
53 // TODO - Make generic, focused on books right now, Perhaps set-up a better image
54 $default = 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==';
55 if (!$this->image_id) {
60 $cover = $this->cover ? url($this->cover->getThumb($width, $height, false)) : $default;
61 } catch (\Exception $err) {
68 * Get the cover image of the shelf
70 public function cover(): BelongsTo
72 return $this->belongsTo(Image::class, 'image_id');
76 * Get the type of the image model that is used when storing a cover image.
78 public function coverImageTypeKey(): string
84 * Check if this shelf contains the given book.
88 public function contains(Book $book): bool
90 return $this->books()->where('id', '=', $book->id)->count() > 0;
94 * 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]);