larasup / localization
Database localization package for Laravel
Requires
- php: >=8.2
- illuminate/database: ^6.0
- illuminate/support: ^6.0
This package is not auto-updated.
Last update: 2024-05-27 14:06:33 UTC
README
It's a little package for database localization in laravel. Now you can change localized fields through the database. Actually, all localized fields from table will be cached in a week. Package will be useful for interface localization, or for some static content.
Installation
composer require larasup/localiztion
Preparing
1. Add the service provider to config/app.php
'providers' => [
...
Larasup\Localization\LocalizationServiceProvider::class,
...
];
2. Run localization migration
php artisan migrate
Usage
1. Prepare your model
Add Localize
trait, $localize
property into your Eloquent model and implements iLocalize interface for phpStorm support.
class Category extends Model implements iLocalize
{
use Localize;
protected array $localize = ['title'];
}
After this step your model will have title
field.
2. Now you can use it
2.1 Getting models with localized field
public static function getLocalizedCategories(): Collection
{
$categories = Category::query()
->with('children.children')
->whereNull('parent_id')
->get();
LocalizationService::enrichCollection($categories, Category::class);
return $categories;
}
After this you can get localized field from model
$categories = getLocalizedCategories();
foreach ($categories as $category) {
echo $category->title;
}
Notice: it's a virtual field and you can't use it in where
clause. May be it can be fixed in next versions.
2.2 Setting localized field
If you want to set localized field, you should use setLocalizedField
method.
LocalizationService::setLocalization(
$objectClass, // $model->getMorphName() for example 'App/Models/Category'
$modelPrimaryValue, // $model->getKey() for example 1
$field, // Name of localized field, in our case 'title'
$value, // Value of localized field, for example 'Categoría de prueba'
$language // Language of localized field, for example 'es'
);