Store your translations in the database with Laravel translation loader package

By Ved Prakash N | Aug 11, 2023 | Laravel
Share :

https://www.fundaofwebit.com/post/laravel-translation-loader

Store your translations in the database with Laravel translation loader package


In this article, you will be learning how to store your language data into database and translate in the laravel application.

Step 1: install Laravel translation loader through Composer:

composer require spatie/spatie/laravel-translation-loader


Step 2: Open your config/app.php and replace Laravel’s translation service provider ( 'providers' ) :

From this : 

Illuminate\Translation\TranslationServiceProvider::class,

To this:

Spatie\TranslationLoader\TranslationServiceProvider::class,

If you don't find Illuminate\Translation\TranslationServiceProvider::class then add this spatie translation service prodivder as given above, 


Step 3: Let's Publish Laravel translation loader migration file

php artisan vendor:publish --provider="Spatie\TranslationLoader\TranslationServiceProvider" --tag="migrations"

it will create a new table called language_lines in the database which will hold your application translations:


Step 4: Publish the config file using this command

php artisan vendor:publish --provider="Spatie\TranslationLoader\TranslationServiceProvider" --tag="config"


Step 5: Now migrate the language_lines table

php artisan migrate

Now, the setup & installation is completed guys. Let's add / insert the language translation into database in laravel 


Example 1:

1. We are inserting the validation translation in different language vie Laravel Spatie Language Translation Model as given below:

use Spatie\TranslationLoader\LanguageLine;

LanguageLine::create([
   'group' => 'validation',
   'key' => 'required',
   'text' => ['en' => 'This is a required field', 'nl' => 'Dit is een verplicht veld', 'ar' => 'هذا مجال مطلوب'],
]);

2. You can fetch the translation with Laravel's default trans function:

{{ trans('validation.required') }}

Note: You have to add all the Laravel validation translation to work as I shown above in Example 1 - point 1. 

also you can publish the laravel default language translation files as follows:

php artisan lang:publish


3. Change the Language with the following function.

app()->setLocale('en');
app()->setLocale('nl');
app()->setLocale('ar');


Example 2:

1. If you need to store/override json translation lines, just create a normal LanguageLine with group => '*'.

use Spatie\TranslationLoader\LanguageLine;

LanguageLine::create([
    'group' => '*',
    'key' => 'Home',
    'text' => ['en' => 'Home', 'nl' => 'Thuis', 'ar' => 'بيت'],
]);

2. You can fetch the translation with Laravel's default trans function:

{{ trans('Home') }}


That's it guys, I hope this helped you. 

https://www.fundaofwebit.com/post/laravel-translation-loader

Share this blog on social platforms