将参数添加到Laravel Accessor

时间:2016-04-28 21:22:42

标签: laravel

我有一个像这样定义的访问者:

public function getNameAttribute($name)
{
    return trans($name, ['age' => $age]);
}

现在,我想在我的翻译中添加参数,所以我希望有类似的东西:

protected $fillable = [
    'id',
    'name',
    'gender',
    'isTeam',
    'ageCategory',
    'ageMin',
    'ageMax',
    'gradeCategory',
    'gradeMin',
    'gradeMax',
];

有可能吗?我该如何定义访问器,以及如何调用发送参数?

编辑1:这是我的模型属性:

public function getAgeString()
{
    $ageCategoryText = '';
    $ageCategories = [
        0 => trans('core.no_age'),
        1 => trans('core.children'),
        2 => trans('core.students'),
        3 => trans('core.adults'),
        4 => trans('core.masters'),
        5 => trans('core.custom')
    ];

    if ($this->ageCategory != 0) {
        if ($this->ageCategory == 5) {
            $ageCategoryText = ' - ' . trans('core.age') . ' : ';
            if ($this->ageMin != 0 && $this->ageMax != 0) {
                if ($this->ageMin == $this->ageMax) {
                    $ageCategoryText .= $this->ageMax . ' ' . trans('core.years');
                } else {
                    $ageCategoryText .= $this->ageMin . ' - ' . $this->ageMax . ' ' . trans('core.years');
                }

            } else if ($this->ageMin == 0 && $this->ageMax != 0) {
                $ageCategoryText .= ' < ' . $this->ageMax . ' ' . trans('core.years');
            } else if ($this->ageMin != 0 && $this->ageMax == 0) {
                $ageCategoryText .= ' > ' . $this->ageMin . ' ' . trans('core.years');
            } else {
                $ageCategoryText = '';
            }
        } else {
            $ageCategoryText = $ageCategories[$this->ageCategory];
        }
    }
    return $ageCategoryText;
}

以下是我在模型中获取$ age变量的方法:

Html5mode

1 个答案:

答案 0 :(得分:2)

您有2个选项,

第一:

如果您希望将翻译的消息作为属性名称,可以尝试:

public function getNameAttribute($name)
{
   return trans($name, ['age' => $this->getAgeString()]);
}

第二

如果您想将翻译作为附加字段,可以使用Mutator为模型添加附加内容:

protected $appends = array('nameWithAge');

并定义获取名称的方法

public function getNameWithAgeAttribute()
{
    return trans($this->attributes['name'], ['age' => $this->getAgeString()]);
}

这将为nameWithAge提供更多属性的属性,您可以这样访问它。

相关问题