12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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 EsgMain extends Model
  8. {
  9. use HasTranslations;
  10. protected $guarded = ['id'];
  11. protected $appends = ["img_pc_url", "og_img_url", "img_mobile_url"];
  12. public $translatable = ['title', 'description', 'meta_title', 'meta_keyword', 'meta_description'];
  13. protected function imgPcUrl(): Attribute
  14. {
  15. return Attribute::make(
  16. get: fn ($value) => is_null($this->img_pc) ? null :Storage::disk('public')->url($this->img_pc),
  17. );
  18. }
  19. protected function imgMobileUrl(): Attribute
  20. {
  21. return Attribute::make(
  22. get: fn ($value) => is_null($this->img_mobile) ? null :Storage::disk('public')->url($this->img_mobile),
  23. );
  24. }
  25. protected function ogImgUrl(): Attribute
  26. {
  27. return Attribute::make(
  28. get: fn ($value) => is_null($this->og_img) ? null :Storage::disk('public')->url($this->og_img),
  29. );
  30. }
  31. public static function getMain(): self
  32. {
  33. $main = self::first();
  34. if(empty($main)){
  35. $main = self::create(self::getDefaultData());
  36. }
  37. return $main;
  38. }
  39. /**
  40. * ✅ 獲取預設設定值
  41. */
  42. public static function getDefaultData(): array
  43. {
  44. return [
  45. 'title' => [
  46. 'zh_TW' => '預設網站標題',
  47. 'en' => 'Default Site Title'
  48. ],
  49. 'description' => [
  50. 'zh_TW' => '預設網站描述',
  51. 'en' => 'Default Site Description'
  52. ],
  53. ];
  54. }
  55. /**
  56. * ✅ 安全的 toArray 方法,確保多語系欄位格式正確
  57. */
  58. public function safeToArray(): array
  59. {
  60. $array = $this->toArray();
  61. // 確保多語系欄位是正確的格式
  62. foreach ($this->translatable as $field) {
  63. if (isset($array[$field])) {
  64. // 如果是字串,轉換為多語系格式
  65. if (is_string($array[$field])) {
  66. $array[$field] = [
  67. 'zh_TW' => $array[$field],
  68. 'en' => ''
  69. ];
  70. }
  71. // 確保有必要的語言鍵
  72. if (is_array($array[$field])) {
  73. $array[$field]['zh_TW'] = $array[$field]['zh_TW'] ?? '';
  74. $array[$field]['en'] = $array[$field]['en'] ?? '';
  75. }
  76. } else {
  77. // 如果欄位不存在,建立預設結構
  78. $array[$field] = ['zh_TW' => '', 'en' => ''];
  79. }
  80. }
  81. return $array;
  82. }
  83. }