Skip to content

Instantly share code, notes, and snippets.

@escapeboy
Last active October 19, 2018 06:17
Show Gist options
  • Save escapeboy/b50f252f095916963e8130bc9dc69f56 to your computer and use it in GitHub Desktop.
Save escapeboy/b50f252f095916963e8130bc9dc69f56 to your computer and use it in GitHub Desktop.
Laravel method for database driven localization
<?php
function t($string) {
if(count(config('app.locales'))==1) return $string;
return \Cache::remember(md5($string.config('app.locale')), 24*60, function() use ($string){
$all_translations = config('app.translations');
$translated = $all_translations->where('hash', md5($string.config('app.locale')))->first();
if(!$translated){
$translated = App\Models\Translations::firstOrCreate([
'string' => $string,
'hash' => md5($string.config('app.locale')),
'value' => '',
'lang' => config('app.locale')
]);
}
if($translated->value) return $translated->value;
return $string;
});
}
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreateTranslationsTable extends Migration {
public function up()
{
Schema::create('translations', function(Blueprint $table) {
$table->increments('id');
$table->text('string');
$table->string('hash', 100)->unique()->index();
$table->text('value')->nullable();
$table->string('lang', 2)->index();
});
}
public function down()
{
Schema::drop('translations');
}
}
<?php
$locale = Request::segment(1);
if(in_array($locale, config('app.locales'))){
config(['app.locale' => $locale]);
}else{
config(['app.locale' => 'bg']);
$locale = '';
}
Route::group([
'prefix' => $locale
], function(){
});
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Translations extends Model {
protected $table = 'translations';
public $timestamps = false;
protected $primaryKey = 'id';
protected $unique = 'hash';
protected $guarded = ['id'];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment