I have a model with a public const array in it for static values, ie:
class StudentStatus extends Model
{
public const STATUSES = [
0 => 'Unknown', // Blank & Other entries
1 => 'Active', // Activo
2 => 'Cancelled', // Cancelado
3 => 'Concluded', // Concluido
];
Until now, I would just translate the end value in a report or something to the desired language. However, I have hit a snag when trying to translate this in a select.
Controller:
$statuses = StudentBursaryStatus::STATUSES; // gets the const and passes it to a view
View:
{!! Form::select('status', [null=>__('Please select one').'...'] $statuses, null, ['class'=>'form-control kt-select2']) !!}
Trying to run __($statuses) expectedly fails ("Illegal offset type") because one is trying to translate an array. Trying to run __() on each value in the model also fails ("Constant expression contains invalid operations"), ie:
public const STATUSES = [
0 => __('Unknown'), // Blank & Other entries
1 => __('Active'), // Activo
2 => __('Cancelled'), // Cancelado
3 => __('Concluded'), // Concluido
];
Short of looping through the array in the controller to translate each value manually - is there a better method to do this?
CodePudding user response:
You can't use functions to define values in pre-set variables. You could define them in constructor but then it's no a constant anymore.
So I recommend to use function that creates translated array from constant
public static function getStatusesTranslated()
{
$translatedStatuses = [];
foreach (self::STATUSES as $key => $status) {
$translatedStatuses[$key] = __($status);
}
return $translatedStatuses;
}
Then:
$statuses = StudentBursaryStatus::getStatusesTranslated();