3 namespace BookStack\Entities\Models;
5 use BookStack\Uploads\Image;
7 use Illuminate\Database\Eloquent\Relations\BelongsTo;
8 use Illuminate\Database\Eloquent\Relations\BelongsToMany;
9 use Illuminate\Database\Eloquent\Relations\HasMany;
10 use Illuminate\Support\Collection;
15 * @property string $description
16 * @property int $image_id
17 * @property Image|null $cover
19 class Book extends Entity implements HasCoverImage
21 public $searchFactor = 2;
23 protected $fillable = ['name', 'description'];
24 protected $hidden = ['restricted', 'pivot', 'image_id', 'deleted_at'];
27 * Get the url for this book.
29 public function getUrl(string $path = ''): string
31 return url('/books/' . implode('/', [urlencode($this->slug), trim($path, '/')]));
35 * Returns book cover image, if book cover not exists return default cover image.
37 * @param int $width - Width of the image
38 * @param int $height - Height of the image
42 public function getBookCover($width = 440, $height = 250)
44 $default = 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==';
45 if (!$this->image_id) {
50 $cover = $this->cover ? url($this->cover->getThumb($width, $height, false)) : $default;
51 } catch (Exception $err) {
59 * Get the cover image of the book.
61 public function cover(): BelongsTo
63 return $this->belongsTo(Image::class, 'image_id');
67 * Get the type of the image model that is used when storing a cover image.
69 public function coverImageTypeKey(): string
75 * Get all pages within this book.
79 public function pages()
81 return $this->hasMany(Page::class);
85 * Get the direct child pages of this book.
89 public function directPages()
91 return $this->pages()->where('chapter_id', '=', '0');
95 * Get all chapters within this book.
99 public function chapters()
101 return $this->hasMany(Chapter::class);
105 * Get the shelves this book is contained within.
107 * @return BelongsToMany
109 public function shelves()
111 return $this->belongsToMany(Bookshelf::class, 'bookshelves_books', 'book_id', 'bookshelf_id');
115 * Get the direct child items within this book.
119 public function getDirectChildren(): Collection
121 $pages = $this->directPages()->visible()->get();
122 $chapters = $this->chapters()->visible()->get();
124 return $pages->concat($chapters)->sortBy('priority')->sortByDesc('draft');