Getting the Translation for a Key

Problem

You want to return a language specific message.

Solution

Use the Lang::get() method.

When you pass Lang::get() a key, it looks up the key in the translation tables for the current locale. If no match is found, the original key is returned.

echo Lang::get('message.hello');

The above will look in app/lang/XX/message.php for a 'hello' key. (Note that XX is the current locale setting).

If your message contains placeholders, you can pass that as a second argument. Let's say app/lang/en/message.php contains the following.

<?php
return array(
    'hello' => 'Hi there',
    'hello2' => 'Hi there, :person',
);
?>

Then the following code would output "Hi there, Chuck".

echo Lang::get('message.hello2', ['person' => 'Chuck']);

If you want to use a specific locale instead of the current locale, you can pass a third argument.

echo Lang::get('message.hello', array(), 'en');

That would always retrieve the English version.

Discussion

Translation strings are stores in the app/lang directory.

/app
   /lang
      /en
         pagination.php
         reminders.php
         validation.php
      /es
         pagination.php
         reminders.php
         validation.php

Add your own files, to create additional "groups" of messages.

comments powered by Disqus