Skip to content

Commit

Permalink
Laravel Translations
Browse files Browse the repository at this point in the history
Laravel translations from database.
  • Loading branch information
atomjoy authored Feb 16, 2023
1 parent 383cc9b commit d3648e8
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 15 deletions.
14 changes: 6 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,23 +46,21 @@ use Trans\Models\Translate;

Route::get('/trans', function () {
try {
// Add translation for locale
Translate::updateOrCreate([
'locale' => 'pl', 'key' => 'Hello'
], ['value' => 'Witaj']);
// Clear cache (in Seeder)
Translate::clearCache();

// Add translation for locale (in Seeder)
Translate::add('Hello','Witaj', 'pl');

// Change locale
app()->setLocale('pl');

// If exists in db
echo "<br> PL " . trans_db('Hello');
// Or
echo "<br> PL " . Translate::trans('Hello');

// If not exists in db get translation from default trans() helper
echo "<br> PL " . trans_db('This text not exists in db');
// Or
echo "<br> PL " . Translate::trans('This text not exists in db');

} catch (Exception $e) {
report($e);
return 'Errors ...';
Expand Down
23 changes: 18 additions & 5 deletions src/Helper.php
Original file line number Diff line number Diff line change
@@ -1,9 +1,22 @@
<?php

use Illuminate\Support\Facades\Cache;
use Trans\Models\Translate;

if (! function_exists('trans_db')) {
function trans_db($str) {
return Translate::trans($str);
}
}
if (!function_exists('trans_db')) {
function trans_db($str, $time = 600)
{
$k = 'trans_db_' . md5($str . app()->getLocale());
if (Cache::store('file')->has($k)) {
$c = Cache::store('file')->get($k);
if (!empty($c)) {
return $c;
}
Cache::forget($k);
}

$t = Translate::trans($str);
Cache::store('file')->put($k, $t, $time);
return $t;
}
}
23 changes: 21 additions & 2 deletions src/Models/Translate.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;

class Translate extends Model
{
Expand All @@ -15,7 +16,25 @@ class Translate extends Model
public static function trans($str)
{
$locale = app()->getLocale();
return self::text($str)->locale($locale)->first()->value ?? trans($str);
return Translate::text($str)->locale($locale)->first()->value ?? trans($str);
}

// Add to db
public static function add($key, $value, $locale = 'en')
{
if (!empty($key) && !empty($value) && !empty($locale)) {
Translate::updateOrCreate([
'locale' => $locale, 'key' => $key
], ['value' => $value]);

return true;
}
return false;
}

public static function clearCache()
{
return Cache::store('file')->flush();
}

// Scope key
Expand All @@ -29,4 +48,4 @@ public function scopeLocale($query, $locale = 'pl')
{
$query->where('locale', $locale);
}
}
}

0 comments on commit d3648e8

Please sign in to comment.