NewsParagraph.php 2.4KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. <?php
  2. namespace App\Models;
  3. use Illuminate\Database\Eloquent\Casts\Attribute;
  4. use Illuminate\Database\Eloquent\Factories\HasFactory;
  5. use Illuminate\Database\Eloquent\Model;
  6. use Illuminate\Database\Eloquent\SoftDeletes;
  7. use Illuminate\Support\Facades\Storage;
  8. use Spatie\Translatable\HasTranslations;
  9. use App\Models\News;
  10. class NewsParagraph extends Model
  11. {
  12. use HasFactory, HasTranslations;
  13. CONST IMAGE = 1;
  14. CONST TEXT = 2;
  15. CONST VIDEO = 3;
  16. protected $guarded = ['id'];
  17. public $timestamps = false;
  18. protected $appends = ['paragraph_video_img', 'paragraph_video_type', 'paragraph_video_url'];
  19. public $translatable = ['video_img_alt'];
  20. protected $casts = [
  21. 'text_content' => 'array', // JSON 轉陣列
  22. ];
  23. public function news(){
  24. return $this->belongsTo(News::class);
  25. }
  26. public function contentType()
  27. {
  28. switch ($this->paragraph_type){
  29. case 1:
  30. return "image";
  31. case 2:
  32. return "text";
  33. case 3:
  34. return "video";
  35. default:
  36. return "";
  37. }
  38. }
  39. public function photos(){
  40. return $this->hasMany(NewsPhoto::class)->orderBy("order");
  41. }
  42. protected function paragraphVideoType(): Attribute
  43. {
  44. return Attribute::make(
  45. get: fn ($value) => ($this->paragraph_type == 3 && !is_null($this->video_type)) ? ($this->video_type == 1 ? "url" : "upload") : null,
  46. );
  47. }
  48. protected function paragraphVideoImg(): Attribute
  49. {
  50. return Attribute::make(
  51. get: fn ($value) => is_null($this->video_img) ? null :Storage::disk('public')->url($this->video_img),
  52. );
  53. }
  54. protected function paragraphVideoUrl(): Attribute
  55. {
  56. return Attribute::make(
  57. get: fn ($value) => ($this->video_type == 2) ? Storage::disk('public')->url($this->video_url) : $this->link,
  58. );
  59. }
  60. /**
  61. * 取得特定語言的文字內容
  62. */
  63. public function getTextContent($locale = 'zh_TW'): string
  64. {
  65. if ($this->paragraph_type != 2) {
  66. return '';
  67. }
  68. $content = $this->text_content;
  69. if (is_array($content)) {
  70. return $content[$locale] ?? '';
  71. }
  72. if (is_string($content)) {
  73. $decoded = json_decode($content, true);
  74. return $decoded[$locale] ?? '';
  75. }
  76. return '';
  77. }
  78. }