It's easy to use text translations in Laravel. However, there are two ways to identify a key: as a string (__('My profile')
) or as an array key (__('users.my_profile')
). Let me tell my opinion on which one is a better choice.
Using translation as a string can be tempting, as it's easier for non-technical people to translate those phrases from JSON than from PHP array.
However, for bigger projects, having one huge en.json
may be a pain to maintain. It can also lead to errors or unexpected behavior. Let's examine two problems.
Problem 1. Lack of Context: Unclear Meaning
The same short phrase could have different meanings based on some conditions. For example, if we have this:
{{ __('Order') }}
The word "Order" could have two meanings:
- To purchase a product
- Position of a record in the table/list
So if there's only one key for both cases, the translator person will put the same translation value.
For example, a German translation:
lang/de.json:
{ "Order": "bestellen"}
That word wouldn't make sense if you use it for table records re-ordering, right?
Of course, we can do it like this:
lang/de.json:
{ "Order a product": "bestellen", "Order of records": "Reihenfolge"}
But it's even better to split the translations into different array key sections or even files, to have context all in one place.
In this case, using an array key could solve the problem.
lang/de/products.php:
return [ 'checkout_page' => [ 'order' => 'bestellen', // ... ], 'table' => [ 'order' => 'Reihenfolge', // ... ],];
Then, in the Blade, calling this key.
{{ __('products.checkout_page.order') }}{{ __('products.table.order') }}
Problem 2. Accidentally Put Word as File Name
Using strings could also lead to conflicts.
For example, using the same product example somewhere in your application, there's a high chance that you would use the products
word. So, you would translate it like __('products')
.
But, because the translation file products.php
already exists, you will get an error.
This is because it tries to return the whole file.
In my experience, using array keys for translations would create a more maintainable Laravel application with less space for mistakes.
While it might require an initial setup, the long-term benefits outweigh the effort. In any case, whichever you choose, remember to have clear keys for both developers and non-technical translators.
If you want to dive deeper into this topic, we have a course: https://laraveldaily.com/course/multi-language-laravel
No comments or questions yet...