我正在使用Laravel(Lumen)创建一个API,其中有一些对象包含一个字段,该字段是文件的路径。
这些路径存储为数据库中的相对路径,但在将它们返回给用户后,我必须将它们转换为绝对URL。
现在我想知道是否有一种方便的方法来向模型对象添加非持久字段。显然有Mutators,但它们会持久保存到数据库中。
我还想过创建一个遍历对象树并转换它找到的每个[
{
"id": 1,
"title": "Some title",
"media": [
{
"id": 435,
"path": "relative/path/to/some/file.ext"
},
{
"id": 436,
"path": "relative/path/to/some/file2.ext"
}
]
}
]
字段的中间件,但这不是一种优雅的方式。
这是我需要的最终转型:
[
{
"id": 1,
"title": "Some title",
"media": [
{
"id": 435,
"url": "http://example.com/relative/path/to/some/file.ext"
},
{
"id": 436,
"url": "http://example.com/relative/path/to/some/file2.ext"
}
]
}
]
要:
dict
欢迎任何想法。
答案 0 :(得分:3)
您可以使用Laravel accessors,
来自Docs:
将列的原始值传递给访问者,允许 你操纵并返回价值。
这些不会保留在数据库中,但会在您访问它们时进行修改。
例如:
class User extends Model
{
/**
* Get the user's first name.
*
* @param string $value
* @return string
*/
public function getFirstNameAttribute($value)
{
return ucfirst($value);
}
}
<强>用法:强>
$user = App\User::find(1);
$firstName = $user->first_name;
在您的使用案例中:
在媒体模型中为路径属性定义访问者。
public function getPathAttribute($value)
{
return storage_path($value);
}
如果您需要使用其他名称(别名)访问该媒体资源:
public function getAliasAttribute()
{
return storage_path($this->attributes['path']);
}
// $model->alias
答案 1 :(得分:2)
正如@Sapnesh Naik所说,你需要的是一个简单的accessor ,就像这样:
public function getPathAttribute($value)
{
$url = config('relative_url') or env('PATH') or $sthElse;
return $url.$this->attributes['path'];
}