On Laravel version 9, I'm trying to use Accessor with an if
condition inside; to put it simply, I need to use the Accessor for my application's postImage
attribute, only if the path of the image does not start with the 'http://' or 'https://' terms, (so that the image sources coming from another website would be displayed correctly with no manipulation in their paths) but nowhere can I find the right way of doing it in terms of the new syntax of Laravel 9 Accessor (and Mutator).
The postImage
attribute Accessor in my Post model (I know it's wrong but I'm trying to find the right way of doing it and that's the point):
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);
);
}
Can you please help me with the new suitable approach to what I'm trying to do?
CodePudding user response:
Use the other function format (with return)
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);
}
);
}
Or use the new format correctly (with value, no return)
protected function postImage():Attribute {
return Attribute::make(
get: fn ($value) => (strpos($value, 'https://') !== FALSE || strpos($value, 'http://') !== FALSE) ? $value : asset('storage/' . $value),
);
}