简体   繁体   中英

How to use if statement in Accessor/Mutator in Laravel 9?

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?

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),
    );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM