【问题标题】:get attribute accessor only for specific method in laravel仅获取 laravel 中特定方法的属性访问器
【发布时间】:2017-11-16 07:58:40
【问题描述】:

我想为 API 调用修改我的查询结果的一些值。这是我的查询

public function modules()
{
    Module::select('id','name','image')->get()->toJson();
}

所以我想修改image 的值,为其添加完整路径。我添加了访问器

public function getImageAttribute($image)
{
    return asset($image);
}

它工作正常,但现在的问题是每次我尝试检索它时它都会影响此列。有没有办法将此访问器(getImageAttribute)仅用于modules 方法?

【问题讨论】:

    标签: php laravel laravel-5 eloquent accessor


    【解决方案1】:

    您可以摆脱访问器并更新 modules 方法内的图像路径。

    public function modules()
    {
        return Module::select('id', 'name', 'image')->get()->map(function ($module) {
            $module->image = asset($module->image);
            return $module;
        })->toJson();
    }
    

    【讨论】:

    • 几分钟,我就能接受了
    • 非常感谢
    猜你喜欢
    • 1970-01-01
    • 2016-11-19
    • 2021-05-02
    • 1970-01-01
    • 2018-12-25
    • 1970-01-01
    • 1970-01-01
    • 2020-08-25
    • 2012-09-25
    相关资源
    最近更新 更多