PHP code example of givanov95 / laravel-translations
1. Go to this page and download the library: Download givanov95/laravel-translations library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
givanov95 / laravel-translations example snippets
namespace App\Enums;
enum Locale: string
{
case en = 'en';
case bg = 'bg';
}
use Givanov95\LaravelTranslations\Middleware\InitAppLocale;
use Givanov95\LaravelTranslations\Middleware\InitLocalePrefix;
$middleware->web(append: [
InitAppLocale::class,
InitLocalePrefix::class,
\App\Http\Middleware\HandleInertiaRequests::class,
]);
use Givanov95\LaravelTranslations\Translator;
use Illuminate\Support\Facades\App;
public function share(Request $request): array
{
return array_merge_recursive(parent::share($request), [
'locale' => fn () => App::getLocale(),
'translations' => fn () => Translator::translations(),
// ...
]);
}
use Givanov95\LaravelTranslations\Concerns\HasTranslation;
class Category extends Model
{
use HasTranslation;
}
// staging + persisting:
$category->setTranslation('en', 'title', 'Shoes')
->setTranslation('bg', 'title', 'Обувки')
->save();
// eager-loading translations for current locale:
Category::withTranslations()->get();
// loading + key-indexing for a single model:
$category->loadTranslations();
$category->translations['title']->text;
use Givanov95\LaravelTranslations\Services\MultiSelectService;
// untranslated (name column):
$options = (new MultiSelectService(Category::class))->dataForSelect();
// translated (translation row with key='title' for current locale):
$options = (new MultiSelectService(Category::class))->dataForSelectWithTranslations('title');
use Givanov95\LaravelTranslations\Concerns\MultiSelectDataConversion;
enum Status: string
{
use MultiSelectDataConversion;
case Active = 'active';
case Draft = 'draft';
}
Status::forSelect(); // ['active' => 'Active', 'draft' => 'Draft']
Status::forSelectWithTranslate(); // [{id: 'active', name: __('Active')}, ...]