Keep media-library covers while adopting sablog /show-{id}.shtml canonical URLs.
Co-authored-by: Cursor <cursoragent@cursor.com>
61 lines
1.4 KiB
PHP
61 lines
1.4 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Models;
|
|
|
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
|
use Illuminate\Database\Eloquent\Relations\HasMany;
|
|
use Spatie\MediaLibrary\HasMedia;
|
|
use Xpier\FilamentMediaLibrary\Models\MediaLibrary;
|
|
use Spatie\MediaLibrary\InteractsWithMedia;
|
|
|
|
class Category extends Model implements HasMedia
|
|
{
|
|
use HasFactory;
|
|
use InteractsWithMedia;
|
|
|
|
protected $fillable = [
|
|
'name',
|
|
'slug',
|
|
'display_order',
|
|
'post_count',
|
|
'description',
|
|
'cover_media_id',
|
|
];
|
|
|
|
public function posts(): HasMany
|
|
{
|
|
return $this->hasMany(Post::class);
|
|
}
|
|
|
|
public function coverMedia(): BelongsTo
|
|
{
|
|
return $this->belongsTo(MediaLibrary::class, 'cover_media_id');
|
|
}
|
|
|
|
public function coverImageUrl(): ?string
|
|
{
|
|
$libraryUrl = $this->coverMedia?->url;
|
|
if (filled($libraryUrl)) {
|
|
return (string) $libraryUrl;
|
|
}
|
|
|
|
return $this->getFirstMedia('cover')?->getUrl();
|
|
}
|
|
|
|
public function getUrlAttribute(): string
|
|
{
|
|
return route('category.show', $this->id);
|
|
}
|
|
|
|
public function registerMediaCollections(): void
|
|
{
|
|
$this->addMediaCollection('cover')
|
|
->useDisk(\App\Support\MediaDisk::name())
|
|
->singleFile();
|
|
}
|
|
}
|