Search

Laravel 5.5: Translating Strings With the `trans` Helper Function

February 19, 2018 —John Koster

The trans method is similar to the get method, and can be used in a similar way. The difference between the two methods is that the trans method does not allow you to change the fallback locale behavior, and defaults to always using the fallback locale for translation lines that have not been defined in other locales.

#Signature

1public function trans(
2 $key,
3 array $replace = [],
4 $locale = null
5);

#Example Use

The following examples will demonstrate how to make equivalent calls between the trans and the get method. For more detailed explanation of each of the parameters, see the section on the get method.

In the following example, we will use the trans method to retrieve an individual translation line:

1// Ask the Service Container for a translator instance.
2$translator = app('translator');
3 
4// Retrieve the validation.accepted translation line.
5$getLine = $translator->get('validation.accepted');
6$transLine = $translator->trans('validation.accepted');

Retrieving translation lines with replacement attributes is also possible with the trans method:

1// Ask the Service Container for a translator instance.
2$translator = app('translator');
3 
4// The :attribute must be an array.
5$translator->get('validation.array');
6 
7$translator->trans('validation.array');
8 
9// The provided value must be an array.
10$translator->get('validation.array', [
11 'attribute' => 'provided value'
12 ]);
13 
14$translator->trans('validation.array', [
15 'attribute' => 'provided value'
16 ]);

The following example demonstrates how to specify a locale using the trans method, and assumes the following language file is available at resources/lang/es/validation.php:

1<?php
2 
3return [
4 
5 'accepted' => 'Los :attribute deben ser aceptados.',
6 
7];

We can now use the trans method to retrieve the translation lines from other locales:

1// As the Service Container for a translator instance.
2$translator = app('translator');
3 
4// Retrieve the validation.accepted translation line.
5$line = $translator->get('validation.accepted', [], 'es');
6$transLine = $translator->trans('validation.accepted', [], 'es');

Some absolutely amazing
people

The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.