仅为 laravel 中的特定方法获取属性访问器

get attribute accessor only for specific method in laravel

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

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

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

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

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

您可以删除访问器并更新 modules 方法中的图像路径。

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