Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading