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
18 * @property \Illuminate\Database\Eloquent\Collection $chapters
19 * @property \Illuminate\Database\Eloquent\Collection $pages
20 * @property \Illuminate\Database\Eloquent\Collection $directPages
22 class Book extends Entity implements HasCoverImage
24 public $searchFactor = 2;
26 protected $fillable = ['name', 'description'];
27 protected $hidden = ['restricted', 'pivot', 'image_id', 'deleted_at'];
30 * Get the url for this book.
32 public function getUrl(string $path = ''): string
34 return url('/books/' . implode('/', [urlencode($this->slug), trim($path, '/')]));
38 * Returns book cover image, if book cover not exists return default cover image.
40 * @param int $width - Width of the image
41 * @param int $height - Height of the image
45 public function getBookCover($width = 440, $height = 250)
47 $default = 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==';
48 if (!$this->image_id) {
53 $cover = $this->cover ? url($this->cover->getThumb($width, $height, false)) : $default;
54 } catch (Exception $err) {
62 * Get the cover image of the book.
64 public function cover(): BelongsTo
66 return $this->belongsTo(Image::class, 'image_id');
70 * Get the type of the image model that is used when storing a cover image.
72 public function coverImageTypeKey(): string
78 * Get all pages within this book.
82 public function pages()
84 return $this->hasMany(Page::class);
88 * Get the direct child pages of this book.
92 public function directPages()
94 return $this->pages()->where('chapter_id', '=', '0');
98 * Get all chapters within this book.
102 public function chapters()
104 return $this->hasMany(Chapter::class);
108 * Get the shelves this book is contained within.
110 * @return BelongsToMany
112 public function shelves()
114 return $this->belongsToMany(Bookshelf::class, 'bookshelves_books', 'book_id', 'bookshelf_id');
118 * Get the direct child items within this book.
122 public function getDirectChildren(): Collection
124 $pages = $this->directPages()->visible()->get();
125 $chapters = $this->chapters()->visible()->get();
127 return $pages->concat($chapters)->sortBy('priority')->sortByDesc('draft');