12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091 |
- <?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 EsgMain extends Model
- {
- use HasTranslations;
- protected $guarded = ['id'];
- protected $appends = ["img_pc_url", "og_img_url", "img_mobile_url"];
- public $translatable = ['title', 'description', 'meta_title', 'meta_keyword', 'meta_description'];
- protected function imgPcUrl(): Attribute
- {
- return Attribute::make(
- get: fn ($value) => is_null($this->img_pc) ? null :Storage::disk('public')->url($this->img_pc),
- );
- }
- protected function imgMobileUrl(): Attribute
- {
- return Attribute::make(
- get: fn ($value) => is_null($this->img_mobile) ? null :Storage::disk('public')->url($this->img_mobile),
- );
- }
- protected function ogImgUrl(): Attribute
- {
- return Attribute::make(
- get: fn ($value) => is_null($this->og_img) ? null :Storage::disk('public')->url($this->og_img),
- );
- }
- public static function getMain(): self
- {
- $main = self::first();
- if(empty($main)){
- $main = self::create(self::getDefaultData());
- }
- return $main;
- }
-
- /**
- * ✅ 獲取預設設定值
- */
- public static function getDefaultData(): array
- {
- return [
- 'title' => [
- 'zh_TW' => '預設網站標題',
- 'en' => 'Default Site Title'
- ],
- 'description' => [
- 'zh_TW' => '預設網站描述',
- 'en' => 'Default Site Description'
- ],
- ];
- }
-
- /**
- * ✅ 安全的 toArray 方法,確保多語系欄位格式正確
- */
- public function safeToArray(): array
- {
- $array = $this->toArray();
-
- // 確保多語系欄位是正確的格式
- foreach ($this->translatable as $field) {
- if (isset($array[$field])) {
- // 如果是字串,轉換為多語系格式
- if (is_string($array[$field])) {
- $array[$field] = [
- 'zh_TW' => $array[$field],
- 'en' => ''
- ];
- }
- // 確保有必要的語言鍵
- if (is_array($array[$field])) {
- $array[$field]['zh_TW'] = $array[$field]['zh_TW'] ?? '';
- $array[$field]['en'] = $array[$field]['en'] ?? '';
- }
- } else {
- // 如果欄位不存在,建立預設結構
- $array[$field] = ['zh_TW' => '', 'en' => ''];
- }
- }
-
- return $array;
- }
- }
|