使用自動載入翻譯在 Laravel 中建立多態可翻譯模型
處理多語言內容時,將翻譯儲存在 JSON 欄位中通常比每個屬性的單獨行更有效。這種方法將翻譯整合到單一列中,從而簡化了資料管理和檢索。
設定翻譯系統
我們將增強翻譯模型和表,以使用 JSON 列來儲存翻譯。這將涉及更新表架構並修改 Translatable 特徵以處理 JSON 資料。
第 1 步:建立翻譯表遷移
如果翻譯表尚不存在,請建立一個新的遷移:
php artisan make:migration create_translations_table
第 2 步:定義表結構
在database/migrations中開啟產生的遷移檔案。對於新表,定義如下:
use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateTranslationsTable extends Migration { public function up() { Schema::create('translations', function (Blueprint $table) { $table->id(); $table->string('locale'); // Stores the locale, e.g., 'en', 'fr' $table->string('translatable_type'); // Stores the related model type, e.g., 'Post', 'Product' $table->unsignedBigInteger('translatable_id'); // Stores the ID of the related model $table->json('translations'); // Stores all translations as a JSON object $table->timestamps(); }); } public function down() { Schema::dropIfExists('translations'); } }
第 3 步:運行遷移
將遷移應用到您的資料庫:
php artisan migrate
第 4 步:建立翻譯模型
接下來,建立翻譯模型來處理多型關係:
php artisan make:model Translation
在翻譯模型中,定義多型關係:
class Translation extends Model { protected $fillable = ['locale', 'translatable_type', 'translatable_id', 'translations']; protected $casts = [ 'translations' => 'array', ]; public function translatable() { return $this->morphTo(); } }
使用 JSON 儲存實現可翻譯特徵
為了讓翻譯處理可在多個模型中重複使用,我們將建立一個 Translatable 特徵,它將根據使用者選擇的區域設定自動載入翻譯內容。此外,如果所選語言環境沒有可用的翻譯,我們將新增一個後備機制來從預設語言環境載入內容。
第 1 步:使用 JSON 處理建立可翻譯特徵
namespace App\Traits; use App\Models\Translation; use Illuminate\Support\Facades\App; trait Translatable { public static function bootTranslatable() { static::retrieved(function ($model) { $model->loadTranslations(); }); } public function translations() { return $this->morphMany(Translation::class, 'translatable'); } public function loadTranslations() { $locale = App::getLocale(); $defaultLocale = config('app.default_locale', 'en'); // Fallback to the default locale // Try to load translations for the current locale $translation = $this->translations()->where('locale', $locale)->first(); if (!$translation && $locale !== $defaultLocale) { // If no translations are found for the current locale, fallback to the default locale $translation = $this->translations()->where('locale', $defaultLocale)->first(); } if ($translation) { $translations = $translation->translations; foreach ($translations as $key => $value) { $this->{$key} = $value; } } } public function addTranslations(array $translations, $locale = null) { $locale = $locale ?? App::getLocale(); return $this->translations()->updateOrCreate( ['locale' => $locale], ['translations' => $translations] ); } }
第 2 步:將可翻譯特徵套用到您的模型
將 Translatable 特徵加入任何需要翻譯支援的模型中。
namespace App\Models; use App\Traits\Translatable; use Illuminate\Database\Eloquent\Model; class Post extends Model { use Translatable; protected $fillable = ['title', 'content']; }
範例:建立翻譯模型
將翻譯加入為 JSON 物件:
$post = Post::create(['title' => 'Default Title', 'content' => 'Default Content']); // Adding translations $post->addTranslations([ 'title' => 'Hello World', 'content' => 'Welcome to our website' ], 'en'); $post->addTranslations([ 'title' => 'Bonjour le monde', 'content' => 'Bienvenue sur notre site Web' ], 'fr');
擷取翻譯模型
當您檢索 Post 模型時,它將根據當前語言環境自動載入翻譯後的內容,或在必要時回退到預設語言環境:
App::setLocale('fr'); $post = Post::find(1); echo $post->title; // Displays "Bonjour le monde" if French translation exists App::setLocale('es'); $post = Post::find(1); echo $post->title; // Displays "Hello World" as it falls back to the English translation
在視圖中顯示翻譯內容
在 Blade 視圖中,您可以像任何其他模型屬性一樣顯示翻譯的內容:
<h1>{{ $post->title }}</h1> <p>{{ $post->content }}</p>
結論
透過使用 JSON 欄位來儲存翻譯並實作回退機制,您可以簡化 Laravel 應用程式中多語言內容的管理。這種方法將翻譯整合到單一列中,簡化了資料處理並使您的程式碼庫更易於維護。無論您是建立部落格、電子商務網站還是任何多語言應用程序,此方法都能確保流暢高效的用戶體驗。
享受吧!
以上是使用自動載入翻譯在 Laravel 中建立多態可翻譯模型的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

JWT是一種基於JSON的開放標準,用於在各方之間安全地傳輸信息,主要用於身份驗證和信息交換。 1.JWT由Header、Payload和Signature三部分組成。 2.JWT的工作原理包括生成JWT、驗證JWT和解析Payload三個步驟。 3.在PHP中使用JWT進行身份驗證時,可以生成和驗證JWT,並在高級用法中包含用戶角色和權限信息。 4.常見錯誤包括簽名驗證失敗、令牌過期和Payload過大,調試技巧包括使用調試工具和日誌記錄。 5.性能優化和最佳實踐包括使用合適的簽名算法、合理設置有效期、

會話劫持可以通過以下步驟實現:1.獲取會話ID,2.使用會話ID,3.保持會話活躍。在PHP中防範會話劫持的方法包括:1.使用session_regenerate_id()函數重新生成會話ID,2.通過數據庫存儲會話數據,3.確保所有會話數據通過HTTPS傳輸。

RESTAPI設計原則包括資源定義、URI設計、HTTP方法使用、狀態碼使用、版本控制和HATEOAS。 1.資源應使用名詞表示並保持層次結構。 2.HTTP方法應符合其語義,如GET用於獲取資源。 3.狀態碼應正確使用,如404表示資源不存在。 4.版本控制可通過URI或頭部實現。 5.HATEOAS通過響應中的鏈接引導客戶端操作。

匿名類在PHP中的主要作用是創建一次性使用的對象。 1.匿名類允許在代碼中直接定義沒有名字的類,適用於臨時需求。 2.它們可以繼承類或實現接口,增加靈活性。 3.使用時需注意性能和代碼可讀性,避免重複定義相同的匿名類。

在PHP中,異常處理通過try,catch,finally,和throw關鍵字實現。 1)try塊包圍可能拋出異常的代碼;2)catch塊處理異常;3)finally塊確保代碼始終執行;4)throw用於手動拋出異常。這些機制幫助提升代碼的健壯性和可維護性。

PHP中有四種主要錯誤類型:1.Notice:最輕微,不會中斷程序,如訪問未定義變量;2.Warning:比Notice嚴重,不會終止程序,如包含不存在文件;3.FatalError:最嚴重,會終止程序,如調用不存在函數;4.ParseError:語法錯誤,會阻止程序執行,如忘記添加結束標籤。

在PHP中,include,require,include_once,require_once的區別在於:1)include產生警告並繼續執行,2)require產生致命錯誤並停止執行,3)include_once和require_once防止重複包含。這些函數的選擇取決於文件的重要性和是否需要防止重複包含,合理使用可以提高代碼的可讀性和可維護性。

PHP和Python各有優勢,選擇依據項目需求。 1.PHP適合web開發,尤其快速開發和維護網站。 2.Python適用於數據科學、機器學習和人工智能,語法簡潔,適合初學者。
