Post.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. <?php
  2. namespace App\Models;
  3. use Illuminate\Database\Eloquent\Factories\HasFactory;
  4. use Illuminate\Database\Eloquent\Model;
  5. use Illuminate\Database\Eloquent\SoftDeletes;
  6. use Illuminate\Support\Str;
  7. use App\Events\PostPublished;
  8. use App\Events\PostScheduled;
  9. class Post extends Model
  10. {
  11. use HasFactory, SoftDeletes;
  12. protected $fillable = [
  13. 'title',
  14. 'slug',
  15. 'content',
  16. 'status',
  17. 'published_at',
  18. 'scheduled_at',
  19. ];
  20. protected $casts = [
  21. 'published_at' => 'datetime',
  22. 'scheduled_at' => 'datetime',
  23. ];
  24. protected $dispatchesEvents = [
  25. 'created' => PostPublished::class,
  26. ];
  27. // Автоматическое создание slug
  28. protected static function boot()
  29. {
  30. parent::boot();
  31. static::creating(function ($post) {
  32. if (empty($post->slug)) {
  33. $baseSlug = \Illuminate\Support\Str::slug($post->title);
  34. $slug = $baseSlug;
  35. $counter = 1;
  36. while (static::where('slug', $slug)->exists()) {
  37. $slug = $baseSlug . '-' . $counter;
  38. $counter++;
  39. }
  40. $post->slug = $slug;
  41. }
  42. });
  43. }
  44. // Связь с комментариями
  45. public function comments()
  46. {
  47. return $this->hasMany(Comment::class);
  48. }
  49. // Только опубликованные посты
  50. public function scopePublished($query)
  51. {
  52. return $query->where('status', 'published')
  53. ->whereNotNull('published_at')
  54. ->where('published_at', '<=', now());
  55. }
  56. // Посты, готовые к автопубликации
  57. public function scopeReadyForPublishing($query)
  58. {
  59. return $query->where('status', 'scheduled')
  60. ->whereNotNull('scheduled_at')
  61. ->where('scheduled_at', '<=', now());
  62. }
  63. // Публикация поста
  64. public function publish()
  65. {
  66. $this->update([
  67. 'status' => 'published',
  68. 'published_at' => now(),
  69. ]);
  70. event(new PostPublished($this));
  71. }
  72. // Снятие с публикации
  73. public function unpublish()
  74. {
  75. $this->update([
  76. 'status' => 'draft',
  77. ]);
  78. }
  79. // Планирование публикации
  80. public function schedule($dateTime)
  81. {
  82. $this->update([
  83. 'status' => 'scheduled',
  84. 'scheduled_at' => $dateTime,
  85. ]);
  86. event(new PostScheduled($this));
  87. }
  88. }