Localizations and Translations in Laravel (Spanish and English)

With the functions that Laravel offers natively for managing the location, that is, the place where the application is being consumed and with this, being able to offer another service, such as automatically translating texts based on to location or by user selection. In this section, we will see how to implement both themes.

Text strings for translation

Laravel provides two ways to manage translation chains that are used to display the translated texts of our application in different languages; in both cases, we must create a folder to store them:

/lang

Where we create our translation files whether they are PHP:

/lang
    /en
        messages.php
    /es
        messages.php

Or in JSONs:

/lang
    en.json
    es.json

In the book, we will use the PHP file format; you can create as many as you want and modularize the messages according to our preferences.

Finally, we are the ones who must define the translated strings and personalize them by changing the text predefined by the application and creating our own; through the key/value pair, indicating the key and the translation; for example:

return [
    'welcome' => 'Welcome to our application!',
];

Publish the language files

By default, when creating a project in Laravel it does not include the lang folder; to generate it, we have the following artisan command:

$ php artisan lang:publish 

The lang:publish command will create the lang directory in your application and publish the default set of language files used by Laravel:

 

Folder for translations

Crear las cadenas de traducción

Las cadenas de texto para las traducciones se almacenan en archivos en la carpeta de lang, en estos archivos, se almacenan textos que son internos a Laravel y provistos por nosotros:

/lang
    /en
        messages.php
    /es
        messages.php

Creemos los siguientes:

lang/en/messages.php

<?php
 
return [
    'welcome' => 'Welcome to our application!',
];

lang/es/messages.php

<?php
 
return [
    'welcome' => 'Bienvenido a nuestra aplicación!',
];

Y los empleamos a lo largo de la aplicación:

echo __('messages.welcome')

Como puedes apreciar, debemos de colocar el nombre del archivo y la clave como clave para la función de __() la cual devuelve el texto traducido; este esquema, lo podemos emplear tanto en el controlador y similar como en la vista.

- Andrés Cruz

En español

This material is part of my complete course and book; You can purchase them from the books and/or courses section, Curso y libro Laravel 11 con Tailwind Vue 3, introducción a Jetstream Livewire e Inerta desde cero - 2024.

Andrés Cruz

Develop with Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter

Andrés Cruz In Udemy

I agree to receive announcements of interest about this Blog.