Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Translate in a specific language in Laravel

Tags:

php

laravel

I have a multilanguage website in Laravel 4.2, and would like to send an email notification to the admins in a specified language using the lang files.

How can I call Lang::get('group.key') specifying the needed language ?

Thank you for your help !

Edit: existing code: (the lang items are option1, option2, .., option6)

class EmailController extends BaseController {
    public static function contact(){
        $rules = [
            'name' => 'required',
            'email' => 'required|email',
            'subject' => 'required|digits_between:1,6',
            'message' => 'required'
        ];
        $validator = Validator::make(Input::all(), $rules);
        if (!$validator->fails()){
            $data = ['subject' => Input::get('subject'), 
                'email' => Input::get('email'),
                'content' => Input::get('message')];
            Mail::send('emails.contact', $data, function($message){
                $message->from(Input::get('email'), Input::get('name'));
                $message->to('[email protected]', 'Admin');
                $message->subject(Lang::get('contact.option'.Input::get('subject')));
            });
        }
        return Redirect::to('/');
    }
}
like image 809
MPikkle Avatar asked Apr 14 '15 12:04

MPikkle


People also ask

What is {{ __ }} In Laravel?

Laravel 5 Translation Using the Double Underscore (__) Helper Function. The __ helper function can be used to retrieve lines of text from language files.

What is @lang in Laravel?

Laravel-lang is a collection of over 68 language translations for Laravel by developer Fred Delrieu (caouecs), including authentication, pagination, passwords, and validation rules. This package also includes JSON files for many languages.


2 Answers

There are 3 ways to achieve this:

  1. You can change default language at runtime by doing this:

App::setLocale('fr'); NB: This is not suitable for your current need as it will only take effect on next page load.

  1. You can set default language here app/config/app.php

'fallback_locale' => 'fr'

  1. I took a deeper look at Illuminate\Translation\Translator:

    get($key, array $replace = array(), $locale = null)

    This means you can do this using Translator Facade:

    Lang::get($key, array $replace = array(), $locale = null);

    Example:

    Lang::get('group.key',[],'fr');

NB: You folder structure should look like this

/app     /lang         /en             messages.php         /fr             messages.php 
like image 199
Emeka Mbah Avatar answered Sep 24 '22 08:09

Emeka Mbah


To get a language specific translation - different from the current locales without setting and unsetting the locales, just do

__('description_1', [], 'en')
like image 20
alex toader Avatar answered Sep 22 '22 08:09

alex toader