Gazz
Gazz

Reputation: 1075

How to decrypt string only if string is not null/empty

I have a form which a user can come back to and complete at any time. I have one select box in particular with data which needs to be encrypted.

The issue I am having is that because this field is optional, there are times when the field can be null/empty and therefore my page fails with the error "The payload is invalid." I am assuming this is because it is trying to decrypt a field which is null and therefore it cannot.

Here is part of the blade below:

        <label for="religion">Religion</label>
        <select class="form-control" name="religion" id="religion">
            <option value="" selected>Choose...</option>
            <option value="Religion 1" @if(old('religion', decrypt($user->diversity->religion) === "Religion 1")) selected @endif>Religion 1</option>
            <option value="Religion 2" @if(old('religion', decrypt($user->diversity->religion) === "Religion 2")) selected @endif>Religion 2</option>
        </select>

Because I am also using the old() function to also return the values of the fields if validation fails, I can't do an if statement with empty() to check if $user->diversity->religion is not empty.

Is there a way of doing this without making my blade too bloated. It would be ideal if there was a way to only decrypt a string if it isn't empty/null.

Upvotes: 2

Views: 1464

Answers (2)

Darryl E. Clarke
Darryl E. Clarke

Reputation: 7647

In order to decrease bloat, you can put the check for the properties in the User model. I'm not going to write all the code but a stub like this in User:

public function decryptProperty($property) {}

Where you can check if property is set, decrypt it, and return the value. Then in your view you can reduce bloat by just checking the user model directly:

<option value="Religion 1" @if(old('religion', $user->decryptProperty($user->diversity->religion) === "Religion 1")) selected @endif>Religion 1</option>

This allows you to keep most of your logic in your model and keep a mostly tidy view (highly recommended).

Upvotes: 1

Jonathon
Jonathon

Reputation: 16333

Just check if the value is empty before passing it to decrypt:

<option value="Religion 1" @if(old('religion', empty($user->diversity->religion) ? '' : decrypt($user->diversity->religion) === "Religion 1")) selected @endif>Religion 1</option>

Or if you want a bit more convenience, you could add an accessor method in the user model:

public function getDecryptedReligionAttribute()
{
    return empty($this->diversity->religion) ? '' : decrypt($this->diversity->religion);
}

That would allow you to simple pass $user->decrypted_religion to the old function:

<option value="Religion 1" @if(old('religion', $user->decrypted_religion) === "Religion 1") selected @endif>Religion 1</option>

Upvotes: 3

Related Questions