搜尋
首頁後端開發php教程使用自動載入翻譯在 Laravel 中建立多態可翻譯模型

Building a Polymorphic Translatable Model in Laravel with Autoloaded Translations

處理多語言內容時,將翻譯儲存在 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 id="post-gt-title">{{ $post->title }}</h1>
<p>{{ $post->content }}</p>

結論

透過使用 JSON 欄位來儲存翻譯並實作回退機制,您可以簡化 Laravel 應用程式中多語言內容的管理。這種方法將翻譯整合到單一列中,簡化了資料處理並使您的程式碼庫更易於維護。無論您是建立部落格、電子商務網站還是任何多語言應用程序,此方法都能確保流暢高效的用戶體驗。

享受吧!

以上是使用自動載入翻譯在 Laravel 中建立多態可翻譯模型的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
繼續使用PHP:耐力的原因繼續使用PHP:耐力的原因Apr 19, 2025 am 12:23 AM

PHP仍然流行的原因是其易用性、靈活性和強大的生態系統。 1)易用性和簡單語法使其成為初學者的首選。 2)與web開發緊密結合,處理HTTP請求和數據庫交互出色。 3)龐大的生態系統提供了豐富的工具和庫。 4)活躍的社區和開源性質使其適應新需求和技術趨勢。

PHP和Python:探索他們的相似性和差異PHP和Python:探索他們的相似性和差異Apr 19, 2025 am 12:21 AM

PHP和Python都是高層次的編程語言,廣泛應用於Web開發、數據處理和自動化任務。 1.PHP常用於構建動態網站和內容管理系統,而Python常用於構建Web框架和數據科學。 2.PHP使用echo輸出內容,Python使用print。 3.兩者都支持面向對象編程,但語法和關鍵字不同。 4.PHP支持弱類型轉換,Python則更嚴格。 5.PHP性能優化包括使用OPcache和異步編程,Python則使用cProfile和異步編程。

PHP和Python:解釋了不同的範例PHP和Python:解釋了不同的範例Apr 18, 2025 am 12:26 AM

PHP主要是過程式編程,但也支持面向對象編程(OOP);Python支持多種範式,包括OOP、函數式和過程式編程。 PHP適合web開發,Python適用於多種應用,如數據分析和機器學習。

PHP和Python:深入了解他們的歷史PHP和Python:深入了解他們的歷史Apr 18, 2025 am 12:25 AM

PHP起源於1994年,由RasmusLerdorf開發,最初用於跟踪網站訪問者,逐漸演變為服務器端腳本語言,廣泛應用於網頁開發。 Python由GuidovanRossum於1980年代末開發,1991年首次發布,強調代碼可讀性和簡潔性,適用於科學計算、數據分析等領域。

在PHP和Python之間進行選擇:指南在PHP和Python之間進行選擇:指南Apr 18, 2025 am 12:24 AM

PHP適合網頁開發和快速原型開發,Python適用於數據科學和機器學習。 1.PHP用於動態網頁開發,語法簡單,適合快速開發。 2.Python語法簡潔,適用於多領域,庫生態系統強大。

PHP和框架:現代化語言PHP和框架:現代化語言Apr 18, 2025 am 12:14 AM

PHP在現代化進程中仍然重要,因為它支持大量網站和應用,並通過框架適應開發需求。 1.PHP7提升了性能並引入了新功能。 2.現代框架如Laravel、Symfony和CodeIgniter簡化開發,提高代碼質量。 3.性能優化和最佳實踐進一步提升應用效率。

PHP的影響:網絡開發及以後PHP的影響:網絡開發及以後Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP類型提示如何起作用,包括標量類型,返回類型,聯合類型和無效類型?PHP類型提示如何起作用,包括標量類型,返回類型,聯合類型和無效類型?Apr 17, 2025 am 12:25 AM

PHP類型提示提升代碼質量和可讀性。 1)標量類型提示:自PHP7.0起,允許在函數參數中指定基本數據類型,如int、float等。 2)返回類型提示:確保函數返回值類型的一致性。 3)聯合類型提示:自PHP8.0起,允許在函數參數或返回值中指定多個類型。 4)可空類型提示:允許包含null值,處理可能返回空值的函數。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱工具

MantisBT

MantisBT

Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器

SublimeText3 Mac版

SublimeText3 Mac版

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