Skip to content

Instantly share code, notes, and snippets.

@sahibalejandro
Created March 31, 2015 00:04
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 sahibalejandro/0fecc66638aef577d9a7 to your computer and use it in GitHub Desktop.
Save sahibalejandro/0fecc66638aef577d9a7 to your computer and use it in GitHub Desktop.
Laravel Model Locale Attributes
<?php
/**
* Author: Sahib J. Leo <sahib@sahib.io>
*
* Don't forget to add "model_fallback_locale" to your config/app.php
*
*/
namespace App\Support;
use App;
use Config;
/**
* Trait MultiLanguageAttributes
*
* @package App\Support
*/
trait LocaleAttributes
{
/**
* Dynamically retrieve attributes on the model.
*
* @param string $attribute
*
* @return mixed
*/
public function __get($attribute)
{
list($current, $fallback) = $this->localizeAttribute($attribute);
if (isset($this->attributes[$current]))
{
$value = parent::__get($current);
// Use this value only if it's not null or an empty
// string, otherwise the fallback value will be used.
if (!is_null($value) && $value !== '') return $value;
}
if (isset($this->attributes[$fallback])) return parent::__get($fallback);
return parent::__get($attribute);
}
/**
* Determine if an locale attribute exists on the model.
* This method is needed to force call the "__get()" method in some scenarios, for
* example, when calling the "lists()" method over an eloquent collection.
*
* @param string $attribute
*
* @return bool
*/
public function __isset($attribute)
{
list($current, $fallback) = $this->localizeAttribute($attribute);
if (isset($this->attributes[$current])) return true;
if (isset($this->attributes[$fallback])) return true;
return parent::__isset($attribute);
}
/**
* Get suffixed attribute names for current locale and fallback locale.
*
* @param string $attribute
*
* @return array
*/
private function localizeAttribute($attribute)
{
$current = $attribute . '_' . App::getLocale();
$fallback = $attribute . '_' . Config::get('app.model_fallback_locale', 'en');
return array($current, $fallback);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment