95 lines
2.4 KiB
PHP
95 lines
2.4 KiB
PHP
<?php
|
|
|
|
namespace App\Models;
|
|
|
|
use App\Enums\PostStatus;
|
|
use Database\Factories\PostFactory;
|
|
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
|
use Illuminate\Database\Eloquent\Attributes\RouteKey;
|
|
use Illuminate\Database\Eloquent\Attributes\Scope;
|
|
use Illuminate\Database\Eloquent\Builder;
|
|
use Illuminate\Database\Eloquent\Casts\Attribute;
|
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
|
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
|
use Illuminate\Support\Str;
|
|
|
|
#[Fillable([
|
|
'user_id', 'category_id', 'title', 'slug', 'excerpt', 'body',
|
|
'featured_image', 'status', 'published_at', 'meta_title', 'meta_description',
|
|
])]
|
|
#[RouteKey('slug')]
|
|
class Post extends Model
|
|
{
|
|
/** @use HasFactory<PostFactory> */
|
|
use HasFactory;
|
|
|
|
protected function casts(): array
|
|
{
|
|
return [
|
|
'status' => PostStatus::class,
|
|
'published_at' => 'datetime',
|
|
];
|
|
}
|
|
|
|
protected static function booted(): void
|
|
{
|
|
static::creating(function (Post $post) {
|
|
if (empty($post->slug)) {
|
|
$post->slug = Str::slug($post->title);
|
|
}
|
|
});
|
|
}
|
|
|
|
/**
|
|
* @return BelongsTo<User, $this>
|
|
*/
|
|
public function user(): BelongsTo
|
|
{
|
|
return $this->belongsTo(User::class);
|
|
}
|
|
|
|
/**
|
|
* @return BelongsTo<Category, $this>
|
|
*/
|
|
public function category(): BelongsTo
|
|
{
|
|
return $this->belongsTo(Category::class);
|
|
}
|
|
|
|
/**
|
|
* @return BelongsToMany<Tag, $this>
|
|
*/
|
|
public function tags(): BelongsToMany
|
|
{
|
|
return $this->belongsToMany(Tag::class);
|
|
}
|
|
|
|
/**
|
|
* @param Builder<Post> $query
|
|
*/
|
|
#[Scope]
|
|
protected function published(Builder $query): void
|
|
{
|
|
$query->where('status', PostStatus::Published)
|
|
->whereNotNull('published_at')
|
|
->where('published_at', '<=', now());
|
|
}
|
|
|
|
protected function bodyHtml(): Attribute
|
|
{
|
|
return Attribute::get(fn () => Str::markdown($this->body, [
|
|
'html_input' => 'strip',
|
|
'allow_unsafe_links' => false,
|
|
]));
|
|
}
|
|
|
|
protected function excerptOrSummary(): Attribute
|
|
{
|
|
return Attribute::get(
|
|
fn () => $this->excerpt ?: Str::limit(strip_tags(Str::markdown($this->body)), 160)
|
|
);
|
|
}
|
|
}
|