Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@renepardon
Created October 2, 2017 15:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save renepardon/9d3408b1ede334e1c5fde65031463194 to your computer and use it in GitHub Desktop.
Save renepardon/9d3408b1ede334e1c5fde65031463194 to your computer and use it in GitHub Desktop.
<?php
namespace App;
use Carbon\Carbon;
use Illuminate\Support\Facades\Session as SessionFacade;
/**
* Trait I18nTrait
*
* @package App
*/
trait I18nTrait
{
/**
* @var array
*/
protected $translations = [];
/**
* @var string
*/
protected $locale;
/**
* @param string $locale
*/
public function setUserLocale(string $locale = 'de')
{
if (!in_array($locale, config('app.supported_locales'))) {
throw new \InvalidArgumentException(trans('Provided locale is not supported'));
}
$this->locale = $locale;
app()->setLocale($locale);
SessionFacade::put('_locale', $locale);
Carbon::setLocale($locale);
}
/**
* @param string $key
*
* @return string
*/
public function translate(string $key): string
{
if (!isset($this->translations[$this->locale])) {
$this->translations[$this->locale] = include(resource_path(sprintf('lang/%s/messages.php', $this->locale)));
}
if (isset($this->translations[$this->locale][$key])) {
return $this->translations[$this->locale][$key];
}
// Default, return key again as no translation was found for current locale...
return $key;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment