diff --git a/README.md b/README.md index 328619b..dc3e788 100644 --- a/README.md +++ b/README.md @@ -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 "
PL " . trans_db('Hello'); - // Or - echo "
PL " . Translate::trans('Hello'); // If not exists in db get translation from default trans() helper echo "
PL " . trans_db('This text not exists in db'); - // Or - echo "
PL " . Translate::trans('This text not exists in db'); + } catch (Exception $e) { report($e); return 'Errors ...'; diff --git a/src/Helper.php b/src/Helper.php index 981992d..d9fd2b1 100644 --- a/src/Helper.php +++ b/src/Helper.php @@ -1,9 +1,22 @@ 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; + } +} diff --git a/src/Models/Translate.php b/src/Models/Translate.php index bfa80d1..c904009 100644 --- a/src/Models/Translate.php +++ b/src/Models/Translate.php @@ -4,6 +4,7 @@ use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; +use Illuminate\Support\Facades\Cache; class Translate extends Model { @@ -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 @@ -29,4 +48,4 @@ public function scopeLocale($query, $locale = 'pl') { $query->where('locale', $locale); } -} \ No newline at end of file +}