[英]Laravel 5.4 translations with constant values
我遇到翻译问题。 我对他们很陌生,因为我从未尝试将翻译添加到项目中。 我在Laravel 5.4中使用此模型来进行通知:
// /App/Notification.php
class Notification extends Model
{
const NO_STATUS = 0;
const SENT = 100;
const ACCEPTED = 200;
const ERROR = 300;
public static $statuses = [
self::NO_STATUS => 'No status',
self::SENT => 'Sent',
self::ACCEPTED => 'Accepted',
self::ERROR => 'Error',
];
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'from', 'to', 'status',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
//
];
/**
* The attributes that should be casted to native types.
*
* @var array
*/
protected $casts = [
'from' => 'integer',
'status' => 'integer',
];
public function isSent()
{
return $this->status == self::SENT;
}
public function isAccepted()
{
return $this->status == self::ACCEPTED;
}
public function isError()
{
return $this->status == self::ERROR;
}
public static function statuses()
{
return self::statuses();
}
public function getStatusAttribute($value)
{
return self::$statuses[$value];
}
}
我有这个转换文件,我打算用它来将用户状态中存储在数据库中的数值转换为可读文本,以便用户在视图中看到通知列表时:
// /resources/lang/en/constants.php
return [
/*
* Notifications constants
*/
'notification' => [
'no_status' => 'No status',
'sent' => 'Sent',
'accepted' => 'Accepted',
'error' => 'Error',
],
];
我在模型中具有getStatusAttribute
访问器函数,以文本形式检索其状态代码,但是我不能(显然)将值设置为静态属性,如下所示:
public static $statuses = [
self::NO_STATUS => trans('constants.notification.no_status'),
self::SENT => trans('constants.notification.sent'),
self::ACCEPTED => trans('constants.notification.accepted'),
self::ERROR => trans('constants.notification.error'),
];
关于如何实现此目标的任何建议?
我希望对象中返回的属性已经成为翻译后的文本,如果可能的话,请在视图中进行翻译。
谢谢你的时间。
您应该返回一个函数,而不是一个常量。
Class Status
{
public static function getStatusArray = [
self::NO_STATUS => __('constants.notification.no_status'),
self::SENT => __('constants.notification.sent'),
self::ACCEPTED => __('constants.notification.accepted'),
self::ERROR => __('constants.notification.error'),
];
}
之后,您可以像这样调用一个函数:
array_get(App\Class::getStatusArray(), 1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.