| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105 |
- <?php
- namespace App\Models;
- use Illuminate\Database\Eloquent\Factories\HasFactory;
- use Illuminate\Database\Eloquent\Model;
- use Illuminate\Database\Eloquent\SoftDeletes;
- use Illuminate\Support\Str;
- use App\Events\PostPublished;
- use App\Events\PostScheduled;
- class Post extends Model
- {
- use HasFactory, SoftDeletes;
- protected $fillable = [
- 'title',
- 'slug',
- 'content',
- 'status',
- 'published_at',
- 'scheduled_at',
- ];
- protected $casts = [
- 'published_at' => 'datetime',
- 'scheduled_at' => 'datetime',
- ];
- protected $dispatchesEvents = [
- 'created' => PostPublished::class,
- ];
- // Автоматическое создание slug
- protected static function boot()
- {
- parent::boot();
-
- static::creating(function ($post) {
- if (empty($post->slug)) {
- $baseSlug = \Illuminate\Support\Str::slug($post->title);
- $slug = $baseSlug;
- $counter = 1;
- while (static::where('slug', $slug)->exists()) {
- $slug = $baseSlug . '-' . $counter;
- $counter++;
- }
- $post->slug = $slug;
- }
- });
- }
- // Связь с комментариями
- public function comments()
- {
- return $this->hasMany(Comment::class);
- }
- // Только опубликованные посты
- public function scopePublished($query)
- {
- return $query->where('status', 'published')
- ->whereNotNull('published_at')
- ->where('published_at', '<=', now());
- }
- // Посты, готовые к автопубликации
- public function scopeReadyForPublishing($query)
- {
- return $query->where('status', 'scheduled')
- ->whereNotNull('scheduled_at')
- ->where('scheduled_at', '<=', now());
- }
- // Публикация поста
- public function publish()
- {
- $this->update([
- 'status' => 'published',
- 'published_at' => now(),
- ]);
-
- event(new PostPublished($this));
- }
- // Снятие с публикации
- public function unpublish()
- {
- $this->update([
- 'status' => 'draft',
- ]);
- }
- // Планирование публикации
- public function schedule($dateTime)
- {
- $this->update([
- 'status' => 'scheduled',
- 'scheduled_at' => $dateTime,
- ]);
-
- event(new PostScheduled($this));
- }
- }
|