Replies: 2 comments 8 replies
-
|
Some examples: // Use it anywhere
trans()->string('Hello world');// Support replacements while preserving a strict string return type.
Flux::toast(
trans()->string(':model updated successfully!', ['model' => $modelName]),
null,
5000,
'success',
);// Respect function return type without hassle (for example in backed enums)
public function label(): string
{
return trans()->string($this->name);
}// Retrieve translation arrays without broad array|string|null handling.
$customValidationMessages = trans()->array('validation.custom');// PHP 8.4 property hooks, so you never forget to translate! (unorthodox, but cool?)
public string $label = 'Some label' {
get => trans()->string($this->label);
} |
Beta Was this translation helpful? Give feedback.
-
|
While the naming works well for the places you mentioned that already have these typed helpers, translations are another animal.
However, the naming would, other than, for example Language file{
"greetings": {
"general": "Hello world",
"laravel": "Hello artisans"
},
"ratings": [
"low",
"medium",
"high"
]
}Usage<h1>{{ trans()->message('greetings.general') }}</h1>
<strong>Current rating:</strong> {{ trans()->list('ratings')[$userRating->score] }}
<div class="flex">
@foreach (trans()->list('ratings') as $score => $label)
<label>
<input type="radio" name="rating" value="{{ $score }}" />
{{ $label }}
</label>
@endforeach
</duv> |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Laravel currently provides two main translation helpers:
__(): array|string|nullandtrans(): Translator|array|string.My suggestion is to introduce
trans()->string()andtrans()->array()typed translation accessors. This would lead to type safe, explicit code, asarray|stringshould not be cast tostring. Such an addition would be very simple, astrans()defaults toTranslatoralready.This proposal also aligns with Laravel's typed helper API recently added to
request()andconfig(), which introduced expressive, type-specific accessors such as:request()->string(),request()->integer()and so on.Beta Was this translation helpful? Give feedback.
All reactions