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 ?int $default_template_id
19 * @property Image|null $cover
20 * @property \Illuminate\Database\Eloquent\Collection $chapters
21 * @property \Illuminate\Database\Eloquent\Collection $pages
22 * @property \Illuminate\Database\Eloquent\Collection $directPages
23 * @property \Illuminate\Database\Eloquent\Collection $shelves
24 * @property ?Page $defaultTemplate
26 class Book extends Entity implements HasCoverImage
29 use HasHtmlDescription;
31 public float $searchFactor = 1.2;
33 protected $fillable = ['name'];
34 protected $hidden = ['pivot', 'image_id', 'deleted_at', 'description_html'];
37 * Get the url for this book.
39 public function getUrl(string $path = ''): string
41 return url('/books/' . implode('/', [urlencode($this->slug), trim($path, '/')]));
45 * Returns book cover image, if book cover not exists return default cover image.
47 public function getBookCover(int $width = 440, int $height = 250): string
49 $default = 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==';
50 if (!$this->image_id || !$this->cover) {
55 return $this->cover->getThumb($width, $height, false) ?? $default;
56 } 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 the Page that is used as default template for newly created pages within this Book.
80 public function defaultTemplate(): BelongsTo
82 return $this->belongsTo(Page::class, 'default_template_id');
86 * Get all pages within this book.
88 public function pages(): HasMany
90 return $this->hasMany(Page::class);
94 * Get the direct child pages of this book.
96 public function directPages(): HasMany
98 return $this->pages()->where('chapter_id', '=', '0');
102 * Get all chapters within this book.
104 public function chapters(): HasMany
106 return $this->hasMany(Chapter::class);
110 * Get the shelves this book is contained within.
112 public function shelves(): BelongsToMany
114 return $this->belongsToMany(Bookshelf::class, 'bookshelves_books', 'book_id', 'bookshelf_id');
118 * Get the direct child items within this book.
120 public function getDirectVisibleChildren(): Collection
122 $pages = $this->directPages()->scopes('visible')->get();
123 $chapters = $this->chapters()->scopes('visible')->get();
125 return $pages->concat($chapters)->sortBy('priority')->sortByDesc('draft');