Post.php 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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 function comments()
  24. {
  25. return $this->hasMany(Comment::class);
  26. }
  27. public function user()
  28. {
  29. return $this->belongsTo(User::class);
  30. }
  31. /**
  32. * Enables a "filter()" method on Post queries.
  33. */
  34. public function scopeFilter($query, array $filters = [])
  35. {
  36. if ($month = $filters['month'] ?? NULL)
  37. {
  38. /* When parsing just a month name, Carbon returns a date built
  39. from the current date at midnight, with the month replaced by the
  40. specified month name */
  41. $query->whereMonth('created_at', Carbon::parse($month)->month);
  42. }
  43. if ($year = (int) $filters['year'] ?? NULL)
  44. {
  45. /* When parsing just a month name, Carbon returns a date built
  46. from the current date at midnight, with the month replaced by the
  47. specified month name */
  48. $query->whereYear('created_at', $year);
  49. }
  50. return $query;
  51. }
  52. }