1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283 |
- <?php
- namespace App;
- use Carbon\Carbon;
- class Post extends Model
- {
- /**
- * These fields are OK for mass assignement.
- *
- * @var array
- */
- protected $fillable = ['body', 'title', 'user_id'];
- /**
- * @param string $body
- */
- public function addComment(string $body)
- {
- // Comment::create([
- // 'body' => $body,
- // 'post_id' => $this->id,
- // ]);
- $this->comments()->create(compact('body'));
- }
- public static function archives()
- {
- $archives = static::selectRaw(<<<EOT
- year(created_at) as year,
- monthname(created_at) as month,
- count(*) published
- EOT
- )->groupBy('year', 'month')
- ->orderByRaw('min(created_at) desc')
- ->get()
- ->toArray();
- return $archives;
- }
- public function comments()
- {
- return $this->hasMany(Comment::class);
- }
- public function user()
- {
- return $this->belongsTo(User::class);
- }
- /**
- * Enables a "filter()" method on Post queries.
- */
- public function scopeFilter($query, array $filters = [])
- {
- if ($month = $filters['month'] ?? NULL)
- {
- /* When parsing just a month name, Carbon returns a date built
- from the current date at midnight, with the month replaced by the
- specified month name */
- $query->whereMonth('created_at', Carbon::parse($month)->month);
- }
- if ($year = (int) $filters['year'] ?? NULL)
- {
- /* When parsing just a month name, Carbon returns a date built
- from the current date at midnight, with the month replaced by the
- specified month name */
- $query->whereYear('created_at', $year);
- }
- return $query;
- }
- public function tags()
- {
- return $this->belongsToMany(Tag::class);
- }
- }
|