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.
83 public function pages(): HasMany
85 return $this->hasMany(Page::class);
89 * Get the direct child pages of this book.
91 public function directPages(): HasMany
93 return $this->pages()->where('chapter_id', '=', '0');
97 * Get all chapters within this book.
99 public function chapters(): HasMany
101 return $this->hasMany(Chapter::class);
105 * Get the shelves this book is contained within.
107 public function shelves(): BelongsToMany
109 return $this->belongsToMany(Bookshelf::class, 'bookshelves_books', 'book_id', 'bookshelf_id');
113 * Get the direct child items within this book.
115 public function getDirectChildren(): Collection
117 $pages = $this->directPages()->scopes('visible')->get();
118 $chapters = $this->chapters()->scopes('visible')->get();
120 return $pages->concat($chapters)->sortBy('priority')->sortByDesc('draft');