| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667 |
- <?php
-
- namespace App\Models;
-
- use Illuminate\Database\Eloquent\Casts\Attribute;
- use Illuminate\Database\Eloquent\Model;
- use Illuminate\Support\Facades\Storage;
- use Spatie\Translatable\HasTranslations;
-
- class NewsParagraph extends Model
- {
- use HasTranslations;
- CONST IMAGE = 1;
- CONST TEXT = 2;
-
- protected $guarded = ['id'];
- public $timestamps = false;
- protected $appends = ['paragraph_img'];
- public $translatable = ['img_alt', 'text_content'];
- protected $casts = [
- 'text_content' => 'array', // JSON 轉陣列
- ];
-
- public function news(){
- return $this->belongsTo(News::class);
- }
- protected function paragraphImg(): Attribute
- {
- return Attribute::make(
- get: fn ($value) => is_null($this->image_url) ? null :Storage::url($this->image_url),
- );
- }
-
- public function contentType()
- {
- switch ($this->paragraph_type){
- case 1:
- return "image";
- case 2:
- return "text";
- default:
- return "";
- }
- }
- /**
- * 取得特定語言的文字內容
- */
- public function getTextContent($locale = 'zh_TW'): string
- {
- if ($this->paragraph_type != 2) {
- return '';
- }
-
- $content = $this->text_content;
-
- if (is_array($content)) {
- return $content[$locale] ?? '';
- }
-
- if (is_string($content)) {
- $decoded = json_decode($content, true);
- return $decoded[$locale] ?? '';
- }
- return '';
- }
- }
|