TA_POLIJECARE_E31231389/backend/app/Models/Article.php

83 lines
1.8 KiB
PHP

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Concerns\HasUuids;
use Illuminate\Support\Str;
class Article extends Model
{
use HasFactory, HasUuids;
protected $fillable = [
'title',
'slug',
'image',
'content',
'is_published',
'published_at',
];
protected $casts = [
'is_published' => 'boolean',
'published_at' => 'datetime',
'created_at' => 'datetime',
'updated_at' => 'datetime',
];
/**
* Boot the model.
*/
protected static function boot()
{
parent::boot();
static::creating(function ($article) {
if (empty($article->slug)) {
$article->slug = Str::slug($article->title);
}
});
static::updating(function ($article) {
if ($article->isDirty('title') && empty($article->slug)) {
$article->slug = Str::slug($article->title);
}
});
}
/**
* Scope to get only published articles.
*/
public function scopePublished($query)
{
return $query->where('is_published', true)
->where('published_at', '<=', now());
}
/**
* Get the route key for the model.
*/
public function getRouteKeyName(): string
{
return 'slug';
}
/**
* Get the excerpt attribute.
*/
public function getExcerptAttribute(): string
{
return Str::limit(strip_tags($this->content), 150);
}
/**
* Get the formatted published date.
*/
public function getFormattedPublishedAtAttribute(): string
{
return $this->published_at->format('d M Y');
}
}