Laravel Translation Helper Function: trans

November 16, 2016 —John Koster

The trans helper function is used to return the translation for the given key. It defines a $key parameter which corresponds to an array key within the group file. It also accepts an array of replacements (which are passed through the $parameters array parameter) and a $locale parameter, which can be used to specify the desired locale.

The signature for the trans helper method is:

trans($id = null, $parameters = [], $domain = 'messages', $locale = null)

Replacements are passed as a key/value pair. The replacement keys will be matched to any placeholders within the translation. Placeholders begin with a single colon (:) followed by a name and a space. For example, in the validation.php language file, the following lines can be found:

1<?php
2 
3return [
4 
5 ...
6 
7 'accepted' => 'The :attribute must be accepted.',
8 'array' => 'The :attribute must be an array.',
9 
10 ...
11 
12];

In the above translation lines, :attribute is a placeholder than can be replaced using the $parameters parameter. The following code examples will demonstrate the results of using the $parameters parameter. The results will appear above the method call as a comment.

1 
2// The :attribute must be an array.
3trans('validation.array');
4 
5// The provided value must be an array.
6trans('validation.array', ['attribute' => 'provided value']);

It should be noted that the placeholder name in the $parameters parameter should not contain the leading : character.

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.