How can I let compact ignore non-existing variables?

Issue

I got a question about PHP compact.

In the Laravel controller, I am returning the next values with compact:

return view('vote.cast', compact('canvote', 'opinionClosed', 'userVoteDecision'));

I have a problem here however. The variable ‘userVoteDecision’ is sometimes optional, and will not always be set by the controller.

Is there a way, to let compact ignore a variable, if it does not exist? (by making the return of the value ‘userVoteDecision’ optional?)

Or is there a better workaround, to fix this?

Thank you in advance.

Regards
Dave

Solution

If you want workaround, so take this solution:

if(isset($userVoteDecision)) {
    return view('vote.cast', compact('canvote', 'opinionClosed', 'userVoteDecision'));
} else {
    return view('vote.cast', compact('canvote', 'opinionClosed'));
}

In general, it is better to set $userVoteDecision = null;
And assign a value to a variable only if there is one.
In all other cases, let the variable exist as null

Answered By – Vlad Salabun

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published