Post.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. namespace App;
  3. use Carbon\Carbon;
  4. class Post extends Model
  5. {
  6. /**
  7. * These fields are OK for mass assignement.
  8. *
  9. * @var array
  10. */
  11. protected $fillable = ['body', 'title', 'user_id'];
  12. /**
  13. * @param string $body
  14. */
  15. public function addComment(string $body)
  16. {
  17. // Comment::create([
  18. // 'body' => $body,
  19. // 'post_id' => $this->id,
  20. // ]);
  21. $this->comments()->create(compact('body'));
  22. }
  23. public static function archives()
  24. {
  25. $archives = static::selectRaw(<<<EOT
  26. year(created_at) as year,
  27. monthname(created_at) as month,
  28. count(*) published
  29. EOT
  30. )->groupBy('year', 'month')
  31. ->orderByRaw('min(created_at) desc')
  32. ->get()
  33. ->toArray();
  34. return $archives;
  35. }
  36. public function comments()
  37. {
  38. return $this->hasMany(Comment::class);
  39. }
  40. public function user()
  41. {
  42. return $this->belongsTo(User::class);
  43. }
  44. /**
  45. * Enables a "filter()" method on Post queries.
  46. */
  47. public function scopeFilter($query, array $filters = [])
  48. {
  49. if ($month = $filters['month'] ?? NULL)
  50. {
  51. /* When parsing just a month name, Carbon returns a date built
  52. from the current date at midnight, with the month replaced by the
  53. specified month name */
  54. $query->whereMonth('created_at', Carbon::parse($month)->month);
  55. }
  56. if ($year = (int) $filters['year'] ?? NULL)
  57. {
  58. /* When parsing just a month name, Carbon returns a date built
  59. from the current date at midnight, with the month replaced by the
  60. specified month name */
  61. $query->whereYear('created_at', $year);
  62. }
  63. return $query;
  64. }
  65. public function tags()
  66. {
  67. return $this->belongsToMany(Tag::class);
  68. }
  69. }