NewsParagraph.php 1.6KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. <?php
  2. namespace App\Models;
  3. use Illuminate\Database\Eloquent\Casts\Attribute;
  4. use Illuminate\Database\Eloquent\Model;
  5. use Illuminate\Support\Facades\Storage;
  6. use Spatie\Translatable\HasTranslations;
  7. class NewsParagraph extends Model
  8. {
  9. use HasTranslations;
  10. CONST IMAGE = 1;
  11. CONST TEXT = 2;
  12. protected $guarded = ['id'];
  13. public $timestamps = false;
  14. protected $appends = ['paragraph_img'];
  15. public $translatable = ['img_alt', 'text_content'];
  16. protected $casts = [
  17. 'text_content' => 'array', // JSON 轉陣列
  18. ];
  19. public function news(){
  20. return $this->belongsTo(News::class);
  21. }
  22. protected function paragraphImg(): Attribute
  23. {
  24. return Attribute::make(
  25. get: fn ($value) => is_null($this->image_url) ? null :Storage::url($this->image_url),
  26. );
  27. }
  28. public function contentType()
  29. {
  30. switch ($this->paragraph_type){
  31. case 1:
  32. return "image";
  33. case 2:
  34. return "text";
  35. default:
  36. return "";
  37. }
  38. }
  39. /**
  40. * 取得特定語言的文字內容
  41. */
  42. public function getTextContent($locale = 'zh_TW'): string
  43. {
  44. if ($this->paragraph_type != 2) {
  45. return '';
  46. }
  47. $content = $this->text_content;
  48. if (is_array($content)) {
  49. return $content[$locale] ?? '';
  50. }
  51. if (is_string($content)) {
  52. $decoded = json_decode($content, true);
  53. return $decoded[$locale] ?? '';
  54. }
  55. return '';
  56. }
  57. }