The*_*der 2 php accessor mutators laravel
在 Laravel 版本 9 上,我尝试使用if内部有条件的 Accessor;简而言之,postImage仅当图像的路径不以“http://”或“https://”术语开头时,我才需要对应用程序的属性使用访问器(以便图像源来自另一个网站的代码将正确显示,路径中不会进行任何操作),但我无法根据 Laravel 9 Accessor (和 Mutator)的新语法找到正确的方法。
我的 Post 模型中的属性postImageAccessor (我知道这是错误的,但我正在尝试找到正确的方法,这就是重点):
protected function postImage():Attribute {
return Attribute::make(
get: fn ($value) =>
if (strpos($value, 'https://') !== FALSE || strpos($value, 'http://') !== FALSE) {
return $value;
}
return asset('storage/' . $value);
);
}
Run Code Online (Sandbox Code Playgroud)
您能帮助我采用新的合适方法来完成我想做的事情吗?
使用其他函数格式(带返回)
protected function postImage():Attribute {
return Attribute::make(
get: function ($value) {
if (strpos($value, 'https://') !== FALSE || strpos($value, 'http://') !== FALSE) {
return $value;
}
return asset('storage/' . $value);
}
);
}
Run Code Online (Sandbox Code Playgroud)
或者正确使用新格式(有值,无返回)
protected function postImage():Attribute {
return Attribute::make(
get: fn ($value) => (strpos($value, 'https://') !== FALSE || strpos($value, 'http://') !== FALSE) ? $value : asset('storage/' . $value),
);
}
Run Code Online (Sandbox Code Playgroud)