71 lines
1.6 KiB
PHP
71 lines
1.6 KiB
PHP
<?php
|
|
|
|
namespace App\Models;
|
|
|
|
use Illuminate\Database\Eloquent\Builder;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
use Illuminate\Support\Str;
|
|
|
|
class Article extends Model
|
|
{
|
|
protected $fillable = [
|
|
'title',
|
|
'slug',
|
|
'excerpt',
|
|
'body',
|
|
'published_at',
|
|
];
|
|
|
|
protected function casts(): array
|
|
{
|
|
return [
|
|
'published_at' => 'datetime',
|
|
];
|
|
}
|
|
|
|
protected static function boot(): void
|
|
{
|
|
parent::boot();
|
|
|
|
static::creating(function (Article $article) {
|
|
if (empty($article->slug)) {
|
|
$article->slug = static::generateUniqueSlug($article->title);
|
|
}
|
|
});
|
|
|
|
static::updating(function (Article $article) {
|
|
if ($article->isDirty('title') && empty($article->slug)) {
|
|
$article->slug = static::generateUniqueSlug($article->title);
|
|
}
|
|
});
|
|
}
|
|
|
|
public static function generateUniqueSlug(string $title): string
|
|
{
|
|
$baseSlug = Str::limit(Str::slug($title), 200, '');
|
|
$slug = $baseSlug;
|
|
$counter = 1;
|
|
|
|
while (static::where('slug', $slug)->exists()) {
|
|
$slug = $baseSlug . '-' . $counter;
|
|
$counter++;
|
|
}
|
|
|
|
return $slug;
|
|
}
|
|
|
|
public function scopePublished(Builder $query): Builder
|
|
{
|
|
return $query->whereNotNull('published_at')->where('published_at', '<=', now());
|
|
}
|
|
|
|
public function getIsPublishedAttribute(): bool
|
|
{
|
|
return $this->published_at !== null && $this->published_at->isPast();
|
|
}
|
|
|
|
public function getRouteKeyName(): string
|
|
{
|
|
return 'slug';
|
|
}
|
|
} |