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
22 * @property \Illuminate\Database\Eloquent\Collection $shelves
24 class Book extends Entity implements HasCoverImage
28 public $searchFactor = 1.2;
30 protected $fillable = ['name', 'description'];
31 protected $hidden = ['pivot', 'image_id', 'deleted_at'];
34 * Get the url for this book.
36 public function getUrl(string $path = ''): string
38 return url('/books/' . implode('/', [urlencode($this->slug), trim($path, '/')]));
42 * Returns book cover image, if book cover not exists return default cover image.
44 * @param int $width - Width of the image
45 * @param int $height - Height of the image
49 public function getBookCover($width = 440, $height = 250)
51 $default = 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==';
52 if (!$this->image_id) {
57 $cover = $this->cover ? url($this->cover->getThumb($width, $height, false)) : $default;
58 } catch (Exception $err) {
66 * Get the cover image of the book.
68 public function cover(): BelongsTo
70 return $this->belongsTo(Image::class, 'image_id');
74 * Get the type of the image model that is used when storing a cover image.
76 public function coverImageTypeKey(): string
82 * Get all pages within this book.
84 public function pages(): HasMany
86 return $this->hasMany(Page::class);
90 * Get the direct child pages of this book.
92 public function directPages(): HasMany
94 return $this->pages()->where('chapter_id', '=', '0');
98 * Get all chapters within this book.
100 public function chapters(): HasMany
102 return $this->hasMany(Chapter::class);
106 * Get the shelves this book is contained within.
108 public function shelves(): BelongsToMany
110 return $this->belongsToMany(Bookshelf::class, 'bookshelves_books', 'book_id', 'bookshelf_id');
114 * Get the direct child items within this book.
116 public function getDirectChildren(): Collection
118 $pages = $this->directPages()->scopes('visible')->get();
119 $chapters = $this->chapters()->scopes('visible')->get();
121 return $pages->concat($chapters)->sortBy('priority')->sortByDesc('draft');
125 * Get a visible book by its slug.
126 * @throws \Illuminate\Database\Eloquent\ModelNotFoundException
128 public static function getBySlug(string $slug): self
130 return static::visible()->where('slug', '=', $slug)->firstOrFail();