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