How to add laravel translation

To add translations in Laravel, follow these steps:

Create a new language file: In Laravel, translation strings are typically stored in language files. You can create a new language file by running the following Artisan command in the terminal: 


php artisan make:lang {language_code} --json

Replace {language_code} with the ISO 639-1 language code of the language you want to add translations for. For example, if you want to add translations for French, you would use php artisan make:lang fr --json.

Add translation strings: Open the language file you just created in the resources/lang directory and add your translation strings in JSON format. For example:

{
    "welcome": "Bienvenue",
    "hello": "Bonjour"
}

Here, welcome and hello are the translation keys and Bienvenue and Bonjour are the translated strings for French.

Use the trans function to translate strings: In your views or controllers, you can use the trans function to translate strings. For example


<h1>{{ trans('messages.welcome') }}</h1>

Here, messages.welcome is the translation key for the Bienvenue string.

Change the application locale: By default, Laravel uses the en locale. To change the application locale to the language you just added translations for, add the following code to the AppServiceProvider:

use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Session;

public function boot()
{
    $locale = Session::get('locale', Config::get('app.locale'));
    App::setLocale($locale);
}

This code sets the application locale to the language stored in the locale session variable, or the default app.locale if the session variable is not set.

Set the language in the session: Finally, you can set the language in the session by creating a route or controller method that sets the locale session variable. For example:

public function setLocale($locale)
{
    Session::put('locale', $locale);
    return redirect()->back();
}


This method sets the locale session variable to the language code passed in the URL parameter and redirects the user back to the previous page.

That's it! Your Laravel application now supports translations for the language you just added.


No comments:

Post a Comment

how to call ssh from vs code

 To call SSH from VS Code, you can use the built-in Remote Development extension. This extension allows you to open a remote folder or works...