66 lines
1.5 KiB
PHP
66 lines
1.5 KiB
PHP
<?php
|
|
|
|
namespace App\Models;
|
|
|
|
use Illuminate\Database\Eloquent\Model;
|
|
use Illuminate\Support\Facades\Storage;
|
|
use Illuminate\Support\Str;
|
|
use Illuminate\Database\Eloquent\Casts\Attribute;
|
|
|
|
class News extends Model
|
|
{
|
|
protected $fillable = [
|
|
'category_id',
|
|
'title',
|
|
'slug',
|
|
'image',
|
|
'content',
|
|
'user_id',
|
|
'is_published'
|
|
];
|
|
|
|
// Otomatis buat slug saat title diisi
|
|
protected static function boot()
|
|
{
|
|
parent::boot();
|
|
static::creating(function ($news) {
|
|
$news->slug = Str::slug($news->title);
|
|
});
|
|
}
|
|
|
|
public function author()
|
|
{
|
|
return $this->belongsTo(User::class, 'user_id');
|
|
}
|
|
|
|
public function category()
|
|
{
|
|
return $this->belongsTo(Category::class);
|
|
}
|
|
|
|
/**
|
|
* Accessor untuk URL Gambar
|
|
* Cara panggil di Blade: {{ $item->image_url }}
|
|
*/
|
|
public function getImageUrlAttribute()
|
|
{
|
|
if ($this->image && Storage::disk('public')->exists($this->image)) {
|
|
return asset('storage/' . $this->image);
|
|
}
|
|
|
|
// Placeholder jika gambar tidak ada
|
|
return 'https://placehold.co/600x400/f4f4f5/10b981?text=Klinik+News';
|
|
}
|
|
|
|
protected function readTime(): Attribute
|
|
{
|
|
return Attribute::make(
|
|
get: function () {
|
|
$words = str_word_count(strip_tags($this->content));
|
|
$minutes = ceil($words / 200); // 200 kata per menit
|
|
return $minutes < 1 ? 1 : $minutes;
|
|
},
|
|
);
|
|
}
|
|
}
|