1 <?php namespace BookStack\Entities\Models;
3 use BookStack\Uploads\Image;
5 use Illuminate\Database\Eloquent\Relations\BelongsTo;
6 use Illuminate\Database\Eloquent\Relations\BelongsToMany;
7 use Illuminate\Database\Eloquent\Relations\HasMany;
8 use Illuminate\Support\Collection;
12 * @property string $description
13 * @property int $image_id
14 * @property Image|null $cover
16 class Book extends Entity implements HasCoverImage
18 public $searchFactor = 2;
20 protected $fillable = ['name', 'description'];
21 protected $hidden = ['restricted', 'pivot', 'image_id', 'deleted_at'];
24 * Get the url for this book.
26 public function getUrl(string $path = ''): string
28 return url('/books/' . implode('/', [urlencode($this->slug), trim($path, '/')]));
32 * Returns book cover image, if book cover not exists return default cover image.
33 * @param int $width - Width of the image
34 * @param int $height - Height of the image
37 public function getBookCover($width = 440, $height = 250)
39 $default = 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==';
40 if (!$this->image_id) {
45 $cover = $this->cover ? url($this->cover->getThumb($width, $height, false)) : $default;
46 } catch (Exception $err) {
53 * Get the cover image of the book
55 public function cover(): BelongsTo
57 return $this->belongsTo(Image::class, 'image_id');
61 * Get the type of the image model that is used when storing a cover image.
63 public function coverImageTypeKey(): string
69 * Get all pages within this book.
72 public function pages()
74 return $this->hasMany(Page::class);
78 * Get the direct child pages of this book.
81 public function directPages()
83 return $this->pages()->where('chapter_id', '=', '0');
87 * Get all chapters within this book.
90 public function chapters()
92 return $this->hasMany(Chapter::class);
96 * Get the shelves this book is contained within.
97 * @return BelongsToMany
99 public function shelves()
101 return $this->belongsToMany(Bookshelf::class, 'bookshelves_books', 'book_id', 'bookshelf_id');
105 * Get the direct child items within this book.
108 public function getDirectChildren(): Collection
110 $pages = $this->directPages()->visible()->get();
111 $chapters = $this->chapters()->visible()->get();
112 return $pages->concat($chapters)->sortBy('priority')->sortByDesc('draft');